I made this sample to test wait/notify functionalities:
public class WaitingTest implements Runnable {
Thread b = new Thread(this,"query");
int total=0;
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(10);
}catch(InterruptedException e){
e.printStackTrace();
}
System.out.println("Total is: " + total);
}
}
@Override
public void run(){
synchronized(b){
for(int i=0; i<1000000000 ; i++){
total += i;
}
}
}
}
The problem is, my output should be zero since Im notifying the wait after 10ms and my thread takes longer than this to execute its work. So, my output should be zero, instead its coming another value. What am I missing?
EDIT:
public class WaitingTest implements Runnable {
Thread b = new Thread(this,"query");
int total=0;
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){
b.notify();
for(long i=0; i<100000 ; i++){
total += i;
}
}
}
}
The javadoc for
wait()statesSo when you do
the current thread releases the
synchronizedit has onband your other thread can therefore acquire it in therun()method coming fromThe
totalstarts increasing. When 10ms is up, the main thread reacquires the lock onb(assuming therun()completes) and prints out the total. Note that yourtotalwill most likely overflow.