gpt4 book ai didi

java - 线程完成时是否发出通知信号?为什么此代码示例有效?

转载 作者:太空狗 更新时间:2023-10-29 22:54:20 26 4
gpt4 key购买 nike

我正在寻找线程的一些谜题,但我无法弄清楚为什么以下内容始终打印 999999:

class Job extends Thread {  
private Integer number = 0;
public void run() {
for (int i = 1; i < 1000000; i++) {
number++;
}
}
public Integer getNumber() {
return number;
}
}
public class Test {
public static void main(String[] args)
throws InterruptedException {
Job thread = new Job();
thread.start();
synchronized (thread) {
thread.wait();
}
System.out.println(thread.getNumber());
}
}

在同一个锁上没有notify(虚假唤醒似乎被忽略了)。
如果线程完成,是否会发出通知或其他什么?
为什么 main 打印结果而不是“卡住”等待?

最佳答案

在 Java 7 的 Javadoc 中 Thread.join(long)

This implementation uses a loop of this.wait calls conditioned on this.isAlive. As a thread terminates the this.notifyAll method is invoked. It is recommended that applications not use wait, notify, or notifyAll on Thread instances.

以这种方式直接使用线程被认为是不实用的。注意:wait() 可能由于多种原因而结束,可能是虚假的。


基于与@Voo 的评论相关的益智游戏。关键是您不应该玩弄 Thread 的内部行为,因为这更有可能导致混淆。

public static String getName() {
return "MyProgram";
}
public static void main(String... args) {
new Thread() {
public void run() {
System.out.println("My program is " + getName());
}
}.start();
}

这个程序打印什么?

关于java - 线程完成时是否发出通知信号?为什么此代码示例有效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11609501/

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