[英]wait/notify. Why all threads are getting notified?
這是一段代碼片段
public class ITC3 extends Thread {
private ITC4 it;
public ITC3(ITC4 it){
this.it = it;
}
public static void main(String[] args) {
ITC4 itr = new ITC4();
System.out.println("name is:" + itr.getName());
ITC3 i = new ITC3(itr);
ITC3 ii = new ITC3(itr);
i.start(); ii.start();
//iii.start();
try{
Thread.sleep(1000);
}catch(InterruptedException ie){}
itr.start();
}
public void run(){
synchronized (it){
try{
System.out.println("Waiting - " + Thread.currentThread().getName());
it.wait();
System.out.println("Notified " + Thread.currentThread().getName());
}catch (InterruptedException ie){}
}
}
}
class ITC4 extends Thread{
public void run(){
try{
System.out.println("Sleeping : " + this);
Thread.sleep(3000);
synchronized (this){
this.notify();
}
}catch(InterruptedException ie){}
}
}
給出的輸出是
Output:
Waiting - Thread-1
Waiting - Thread-2
Sleeping : Thread[Thread-0,5,main]
Notified Thread-1
Notified Thread-2
在此,所有線程都會收到通知。 在這種情況下,我無法理解整個輸出。
任何指針都會有所幫助。
謝謝。
您正在同步Thread
的實例。 如果查看文檔 ,您將看到Thread
實例在其run
方法完成時得到通知。 這是join
機制的實現方式。
您執行一個顯式notify
調用(我們在代碼中看到的那個),並在線程完成時執行另一個隱式notifyAll
。 您甚至可以刪除顯式notify
並且由於最后的隱式notifyAll
,行為不會更改。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.