vinaybhatoa vinaybhatoa - 7 months ago 22
Java Question

Notify() Not Working with Wait()

I am new to threads and learning but in the code below why notify is not working. As per my understanding notify should execute the main thread and print the total when i=5. Please correct if i am wrong.

public 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();
}catch(InterruptedException e){
e.printStackTrace();
}

System.out.println("Total is: " + b.total);
}
}
}

class ThreadB extends Thread{
int total;
@Override
public void run(){
synchronized(this){
for(int i=0; i<10 ; i++){
total += i;
if(i==5){
System.out.println("Notify");
notify();
}
System.out.println("Total is in cal thread: "+i+":" + total);
}

}
}
}


Here is the output from the program:

Waiting for b to complete...
Total is in cal thread: 0:0
Total is in cal thread: 1:1
Total is in cal thread: 2:3
Total is in cal thread: 3:6
Total is in cal thread: 4:10
Notify
Total is in cal thread: 5:15
Total is in cal thread: 6:21
Total is in cal thread: 7:28
Total is in cal thread: 8:36
Total is in cal thread: 9:45
Total is: 45 –

Answer Source
synchronized(b){
    try{
        System.out.println("Waiting for b to complete...");
        b.wait();

Don't call wait until you can 100% confirm, inside the synchronized block, that the thing you're waiting for hasn't already happened.