2016-11-27

Java Thread.join() 讓 Thread 可以按順序執行

一般的情況下在多執行緒執行時,無法保證哪個執行緒會先完成。
System.out.println(Thread.currentThread().getName() + " is Started");
Thread aThread = new Thread() {

  public void run() {
    try {
      System.out.println("aThread is Started");
      Thread.sleep(2000);
      System.out.println("aThread is Completed");
    }
    catch (InterruptedException e) {
      e.printStackTrace();
    }
  }
};
aThread.start();
System.out.println(Thread.currentThread().getName() + " is Completed");
例如上面的情況,由於 aThread 需要兩秒,所以 main 先完成。

main is Started
main is Completed
aThread is Started
aThread is Completed
有沒有可能讓 main 等 aThread 完成後再完成呢?

只要透過 join() 就可以。
System.out.println(Thread.currentThread().getName() + " is Started");
Thread aThread = new Thread() {

  public void run() {
    try {
      System.out.println("aThread is Started");
      Thread.sleep(2000);
      System.out.println("aThread is Completed");
    }
    catch (InterruptedException e) {
      e.printStackTrace();
    }
  }
};
aThread.start();
aThread.join();
System.out.println(Thread.currentThread().getName() + " is Completed");
在 main 呼叫 aThread.join(),就可以讓 main 等 aThread 完成後再繼續。

甚至可以讓兩個以上的 Thread 乖乖排隊。
System.out.println("main is Started");

Thread aThread = new Thread() {

  public void run() {
    try {
      System.out.println("aThread is Started");
      Thread.sleep(2000);
      System.out.println("aThread is Completed");
    }
    catch (InterruptedException e) {
      e.printStackTrace();
    }
  }
};

Thread bThread = new Thread() {

  public void run() {
    try {
      aThread.join();
      System.out.println("bThread is Started");
      Thread.sleep(2000);
      System.out.println("bThread is Completed");
    }
    catch (InterruptedException e) {
      e.printStackTrace();
    }
  }
};

aThread.start();
bThread.start();
bThread.join();

System.out.println("main is Completed");
先在 main 裡呼叫 bThead.join(),表示 main 會等 bThread,然後 bThread 又去呼叫 aThread.join(),表示 bThread 會等 aThread,結果就是 aThread 先完成,再來是 bThread,最後是 main。
main is Started
aThread is Started
aThread is Completed
bThread is Started
bThread is Completed
main is Completed
如果把上面的 aThread.join() 與 bThread.join() 拿掉,就會得到以下的結果。
main is Started
main is Completed
aThread is Started
bThread is Started
aThread is Completed
bThread is Completed
---
---
---

沒有留言:

張貼留言