2013-08-22 57 views
4

我需要在這裏解釋。線程正在等待另一個線程

public static void main(String[] args) { 
    FirstThread obj = new FirstThread(); 
    for (int i = 1; i <= 10; i++) { 
     new WaiterThread(obj).start(); 
    } 
    obj.start(); 
    } 

public class FirstThread extends Thread { 
    @Override 
    public void run() { 
    // Do something 
    } 
} 


public class WaiterThread extends Thread { 
    Object obj; 

    WaiterThread(Object obj) { 
    this.obj = obj; 
    } 

    @Override 
    public void run() { 
    synchronized (obj) { 
      obj.wait(); 
    } 
    } 
} 

10個線程爲WaiterThread創建並正在等待的單個FirstThread對象。之後FirstThread終止,所有WaiterThread重操舊業沒有obj.notify()obj.notifyAll()被稱爲任何地方。

這是否意味着WaiterThread s已停止等待FirstThread因爲它被終止?

回答

6

根據the documentation of the Thread class,垂死的線程在代表它的實例上調用notifyAll

此外,引用相同的文檔:

建議應用程序不使用waitnotify,或notifyAllThread實例。

當然,同樣的建議適用於Thread,這是你的代碼做例子。

6

這是線程終止時的一個副作用,它會調用this.notifyAll()(如在Thread.join()的javadoc中所述)。同樣的javadoc還提出如下建議:

建議應用程序不使用的等待,通知,或notifyAll的對線程實例

+3

人們會懷疑我們坐在同一個房間:) –

+0

很高興見到你:-) –

+0

當然,同樣:) –

0

我修改的代碼有點如下

主()方法保持相同

public static void main(String[] args) { 
    FirstThread obj = new FirstThread(); 
    for (int i = 1; i <= 10; i++) { 
     new WaiterThread(obj).start(); 
    } 
    obj.start(); 
    } 

變化是如下

class WaiterThread extends Thread { 
    Object obj; 

    WaiterThread(Object obj) { 
     this.obj = obj; 
    } 

    @Override 
    public void run() { 
     synchronized (obj) { 
      try { 
       obj.wait(); 
      } catch (InterruptedException e) { 
       e.printStackTrace(); 
      } 
      try { 
       Thread.sleep(1000); 
      } catch (InterruptedException e) { 
       e.printStackTrace(); 
      } 
      System.out.println("Thread " + this.getId() + "started"); 
     } 
     System.out.println("Out of sync block by " + this.getId()); 
    } 
} 

螞蟻我得到的輸出是

FirstThread Started 
Thread 19started 
Out of sync block by 19 
Thread 18started 
Out of sync block by 18 
Thread 17started 
Out of sync block by 17 
Thread 16started 
Out of sync block by 16 
Thread 15started 
Out of sync block by 15 
Thread 14started 
Out of sync block by 14 
Thread 13started 
Out of sync block by 13 
Thread 12started 
Out of sync block by 12 
Thread 11started 
Out of sync block by 11 
Thread 10started 
Out of sync block by 10 

所以,你有你的答案。他們不是同時開始! FirstThread在調用notifyAll()時會調用notifyAll(),但每個線程一次只能有一個鎖。所以雖然每個線程都會收到通知,但一次只能執行一個線程。