簡體   English   中英

等待/通知。 為什么所有線程都會收到通知?

[英]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 

在此,所有線程都會收到通知。 在這種情況下,我無法理解整個輸出。

  1. 為什么所有線程都會收到通知?
  2. 睡覺為什么打印`Thread [Thread-0,5,main]
  3. 在整個計划的工作中很丟失。

任何指針都會有所幫助。

謝謝。

您正在同步Thread的實例。 如果查看文檔 ,您將看到Thread實例在其run方法完成時得到通知。 這是join機制的實現方式。

您執行一個顯式notify調用(我們在代碼中看到的那個),並在線程完成時執行另一個隱式notifyAll 您甚至可以刪除顯式notify並且由於最后的隱式notifyAll ,行為不會更改。

  1. 已經回答了,但你不應該在Thread對象上同步。
  2. Thread的toString()方法返回其ThreadGroup中所有線程的名稱,而不僅僅是當前線程的名稱。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM