I can't find reason why ThreadA gets notification from ThreadB only when ThreadB completely finishes it's job. If I comment notify() ThreadA gets notification anyway.
Does ThreadB sends notification automatically when finishes it's job?
Why ThreadB does't notify ThreadA on time?
class ThreadA {
public static void main(String [] args) {
ThreadB b = new ThreadB();
b.start();
synchronized(b)
{
try {
System.out.println("Waiting for b to complete...");
b.wait();
System.out.println("waiting done");
} catch (InterruptedException e) {}
System.out.println("Total is: " + b.total);
}
}
}
class ThreadB extends Thread {
int total=0;
public void run() {
synchronized(this)
{
for(int i=0;i<10;i++)
{
System.out.println(Thread.currentThread().getName()+" "+ Integer.toString(i));
total += i;
}
notify();
System.out.println("notify done");
for(int i=0;i<100;i++)
{
System.out.println(Thread.currentThread().getName()+" "+ Integer.toString(i));
total += i;
}
}
}
}
Output:
Waiting for b to complete...
Thread-0 0
Thread-0 1
Thread-0 2
Thread-0 3
Thread-0 4
Thread-0 5
Thread-0 6
Thread-0 7
Thread-0 8
Thread-0 9
notify done
Thread-0 0
Thread-0 1
Thread-0 2
Thread-0 3
Thread-0 4
Thread-0 5
Thread-0 6
Thread-0 7
Thread-0 8
Thread-0 9
Thread-0 10
Thread-0 11
Thread-0 12
Thread-0 13
Thread-0 14
Thread-0 15
Thread-0 16
Thread-0 17
Thread-0 18
Thread-0 19
waiting done
Total is: 235
Additional question - why Total is 235 in output?
Firstly, please don't use Thread
objects like this. Thread
uses wait
and notify
itself, so you can easily end up with confusing signals.
The reason you're not seeing "waiting done" until the end is that although ThreadB.run
calls notify()
, it then keeps going within the synchronized
block. The wait()
method won't return until it can reacquire the monitor - which it can't do until the end of the synchronized block.
The total is simply the total having added up all the numbers - it looks like you've actually run with a second limit of 20, not 10... and (0 + 1 + 2 + ... 9) + (0 + 1 + 2 + ... 19) is 235. It's not clear why you'd expect anything else.
See more on this question at Stackoverflow