Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/323.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 等待/通知。为什么所有线程都会收到通知?_Java_Multithreading - Fatal编程技术网

Java 等待/通知。为什么所有线程都会收到通知?

Java 等待/通知。为什么所有线程都会收到通知?,java,multithreading,Java,Multithreading,下面是一段代码片段 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

下面是一段代码片段

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-0,5,main]
  • 在整个程序的运行过程中,我迷失了方向
  • 任何指示都会有帮助


    谢谢

    您正在
    线程的实例上进行同步。如果您进行检查,您将看到
    线程
    实例在其
    运行
    方法完成时收到通知。这就是
    join
    机制的实现方式

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

  • 已回答,但不应在线程对象上同步
  • 线程的toString()方法返回其线程组中所有线程的名称,而不仅仅是当前线程的名称

  • 我有一个问题,因为itr实例是在两个线程之间共享的,两个线程会互相阻塞吗?我不明白你所说的“互相阻塞”是什么意思。它们是在同一个监视器上等待的两个线程。它们两个在同一个对象上等待,因此应该通知一个线程,而不是同时通知两个线程,因为我们这里没有使用notifyAll()。我的回答解释了其余部分。在文档中写到,run()方法完成时会通知Thread()实例。我只是想检查一下javadoc。你能给我提供它的参考吗?另请看:顺便说一下,这段代码永远不会做任何合理的事情,因为你的
    synchronized
    块不保护任何共享状态。