I’ve just found strange behavior in java threads.
Here is a code example:
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());
}
}
Unexpectedly it’ll print out the 999999.
Seems like there is notify() call at the end of start() method logic.
Any ideas?
Yes, this is true. When a thread finishes it does a
notify()which is howThread.join()works. Here’s a sample of the Java1.6 code forThread.join():That said, this may be implementation dependent and should not be relied on.