Why doesn't thread wait for notify()
? The thread starts and then goes to the waiting pool, but it proceeds to execute after that moment.
public class JavaApplication2 {
public static void main(String [] args) {
ThreadB b = new ThreadB();
synchronized(b) {
b.start();
try {
System.out.println("1");
b.wait();
} catch (InterruptedException e) {}
System.out.println("Total is: " + b.total);
}
}
}
class ThreadB extends Thread {
int total;
@Override
public void run() {
synchronized(this) {
total += 1;
//notify();
}
}
}
You are synchronizing on the thread object itself, which is wrong usage. What happens is that the dying thread-of-execution always calls notify
on its Thread
object: Thread.join
relies on this. Therefore it is clear why you get the same behavior with and without your own notify
in there.
Solution: use a separate object for thread coordination; this is the standard practice.
The method notifyAll()
is invoked for the Thread
object of the terminating thread. This fact is strangely documented in the description of the Thread.join
, with the following sentence:
As a thread terminates the this.notifyAll method is invoked. It is recommended that applications not use wait, notify, or notifyAll on Thread instances.
Thus, if you don't explicitly read the description of join
, which you don't necessarily have to, you don't get to know the reason for the strange behavior.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With