2010/01/13

Java Concurrency(6)

Joins

join方法讓一個thread等待另外一個thread的完成,如果t是一個正在執行的Thread物件

t.join();

導致目前的thread暫停執行直到t的thread結束,join的Overloads讓程式設計師能夠特定一個等待時間,然而如同
sleep方法,join也依據OS來計時,所以你不應該假定join會正確地等待你所想要的時間。

如同sleep, join回應一個中斷藉由離開的InterruptedException

public class JoinThreadExample {
 
 private static class FirstThread implements Runnable {

  @Override
  public void run() {
   // TODO Auto-generated method stub
   try {
    for(int i = 0; i < 5; i++) {
     System.out.println("I'm first");
     Thread.sleep(2000);
    }
   } catch(InterruptedException e) {
    System.out.println(e);
   }
  }
 }
 
 private static class WeShouldWaitThread implements Runnable {

  @Override
  public void run() {
   // TODO Auto-generated method stub
   for(int i = 0; i < 5; i++) {
    System.out.println("No, you should wait me");
   }
  }
  
 }
 
 public static void main(String[] args) throws InterruptedException {
  Thread f = new Thread(new FirstThread());
  Thread t = new Thread(new WeShouldWaitThread());
  
  f.start();
  t.start();
  t.join();
 }
}
輸出結果

I'm first
No, you should wait me
No, you should wait me
No, you should wait me
No, you should wait me
No, you should wait me
I'm first
I'm first
I'm first
I'm first

從這個結果我們不難發現join的thread t使得其他thread都進入等待狀態直到t完成。

參考文獻
http://java.sun.com/docs/books/tutorial/essential/concurrency/join.html

No comments:

Post a Comment