问题描述
我在寻找某些谜题的线程,我不知道为什么下面一贯打印 999999
:
I am looking in some puzzles for threads and I can't figure out why the following consistently prints 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());
}
}
没有 / code>在同一个锁(和虚假的唤醒似乎被忽略)。
如果一个线程完成了一个通知得到信号或某事?
如何来到<$
There is no notify
on the same lock (and spurious wakeup seem to be ignored).
If a thread finishes does a notify get signalled or something?
How come main
prints the result and not get "stuck" waiting?
推荐答案
在Javadoc for Java 7
In the Javadoc for Java 7 Thread.join(long)
使用Thread直接这种方式被认为是不实际的。
Using a Thread directly this way is considered bad practical. Note: wait() could end for any number of reasons, possibly spuriously.
基于与@ Voo相关的解谜器评论。关键是你不应该使用Thread的内部行为,因为这更有可能导致混乱。
Based on a puzzler related to @Voo's comment. The point is you shouldn't play with the internal behaviour of Thread as this is more likely to lead to confusion.
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();
}
此程式列印什么?
这篇关于是否在螺纹完成时发出通知?为什么此代码示例工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!