4

这是一个代码片段

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. 为什么 Sleeping 正在打印 `Thread[Thread-0,5,main]
  3. 完全迷失在程序的整个工作中。

任何指针都会有所帮助。

谢谢。

4

2 回答 2

3

您正在对Thread. 如果您查看文档,您会看到Thread实例在其run方法完成时收到通知。这就是join机制的实现方式。

您执行一个显式notify调用(我们在代码中看到的那个),并notifyAll在线程完成时执行另一个隐式调用。你甚至可以删除你的显式notify并且行为不会因为最后的隐式而改变notifyAll

于 2013-08-09T11:13:41.320 回答
1
  1. 已经回答,但你不应该同步 Thread 对象。
  2. Thread 的 toString() 方法返回其 ThreadGroup 中所有线程的名称,而不仅仅是当前线程的名称。
于 2013-08-09T11:24:56.697 回答