多線程之join方法


join作用是讓其他線程變為等待,我先執行。thread.Join把指定的線程加入到當前線程,可以將兩個交替執行的線程合並為順序執行的線程(先執行指定的線程,再執行當前的線程)。比如在線程B(如主線程)中調用了線程A的Join()方法,直到線程A執行完畢后,才會繼續執行線程B。

public class Demo11Join {
  public static void main(String[] args) {
    JoinThread joinThread = new JoinThread();
    Thread thread1 = new Thread(joinThread, "線程1");
    Thread thread2 = new Thread(joinThread, "線程2");
    Thread thread3 = new Thread(joinThread, "線程3");
    thread1.start();
    thread2.start();
    thread3.start();
    try {
      thread1.join();
   } catch (Exception e) {
   }
    for (int i = 0; i < 5; i++) {
      System.out.println("main ---i:" + i);
   }
 }
  static class JoinThread implements Runnable {
    private Random random = new Random();
    public void run() {
      String name = Thread.currentThread().getName();
      for (int i = 0; i < 5; i++) {
        try {
          Thread.sleep(random.nextInt(10));
       } catch (InterruptedException e) {
          e.printStackTrace();
       }
        System.out.println(name + "內容是:" + i);
     }
   }
 }
}

其中一次執行結果如下:

線程2內容是:0
線程1內容是:0
線程1內容是:1
線程2內容是:1
線程3內容是:0
線程2內容是:2
線程2內容是:3
線程3內容是:1
線程1內容是:2
線程3內容是:2
線程2內容是:4
線程3內容是:3
線程1內容是:3
線程1內容是:4
main ---i:0
main ---i:1
main ---i:2
main ---i:3
main ---i:4
線程3內容是:4

如果不調用線程1的join方法:

public class Demo11Join {
  public static void main(String[] args) {
    JoinThread joinThread = new JoinThread();
    Thread thread1 = new Thread(joinThread, "線程1");
    Thread thread2 = new Thread(joinThread, "線程2");
    Thread thread3 = new Thread(joinThread, "線程3");
    thread1.start();
    thread2.start();
    thread3.start();
    for (int i = 0; i < 5; i++) {
      System.out.println("main ---i:" + i);
   }
 }
  static class JoinThread implements Runnable {
    private Random random = new Random();
    public void run() {
      String name = Thread.currentThread().getName();
      for (int i = 0; i < 5; i++) {
        try {
          Thread.sleep(random.nextInt(10));
       } catch (InterruptedException e) {
          e.printStackTrace();
       }
        System.out.println(name + "內容是:" + i);
     }
   }
 }
}

其中一次執行結果如下:

main ---i:0
main ---i:1
main ---i:2
main ---i:3
main ---i:4
線程3內容是:0
線程2內容是:0
線程3內容是:1
線程2內容是:1
線程3內容是:2
線程1內容是:0
線程2內容是:2
線程2內容是:3
線程1內容是:1
線程2內容是:4
線程3內容是:3
線程1內容是:2
線程3內容是:4
線程1內容是:3
線程1內容是:4

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM