gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-11-01 02:47:47 25 4
gpt4 key购买 nike

这是一段代码

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. 完全迷失在程序的整个运行过程中。

任何指示都会有所帮助。

谢谢。

最佳答案

您正在同步 Thread 的实例。如果你检查 the documentation ,您会看到 Thread 实例在其 run 方法完成时收到通知。这就是 join 机制的实现方式。

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

关于java - 等待/通知。为什么所有线程都会收到通知?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18145241/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com