顯示具有 Thread 標籤的文章。 顯示所有文章
顯示具有 Thread 標籤的文章。 顯示所有文章

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 先完成。