I made this sample to understand how Wait-Notify works:
public class WaitingTest implements Runnable {
Thread b = new Thread();
int total;
public static void main(String[] args){
WaitingTest w = new WaitingTest();
}
public WaitingTest(){
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: " + total);
}
}
@Override
public void run(){
synchronized(b){
for(int i=0; i<100 ; i++){
total += i;
System.out.println(total);
}
b.notify();
}
}
}
But I'm stuck here for hours and I can't understand why it's not quite working. My output should be more than 0, but its always zero...I was wondering if its becuase of the usage of different threads, but Im not really sure..What am I missing?
I think you have some serious holes in your understanding. You've declared a
Threadand started it in the constructor
That
Threadwill start and die right away since it has noRunnableattached to it.It just so happens that when a
Threaddies, it callsnotify()on itself and since you aresynchronizedon that sameThreadobject, yourwait()ing thread will be awoken. You also have a race here. If theThreadends before the main thread reaches thewait(), you will be deadlocked.Also, there is no reason for
run()to be called, which is whytotalremains 0.Any object can be
synchronizedon, it doesn't have to be aThread. And sinceThreadhas that weird behavior ofnotify()ing itself, you probably shouldn't use it.You should go through both the
Threadtutorials and the synchronization tutorials.