Tuesday, February 7, 2012

Java Threads - Wait and Notify Example

This is a simple Thread example which demonstrates wait and notify functionality of a Thread. In this example we have a main class i.e. MainThread which will call AnotherThread, so that you can see both running simultaneously. Now our main thread enters into wait state till AnotherThread notifies it.


Please see the self explanatory code. Directly you can this code and see the output.


MainThread.java



/* MainThread.java */


public class MainThread {


public static void main(String[] args) {

//Start another thread
Thread anotherThreadObject = new Thread(new AnotherThread());
anotherThreadObject.start();

//Main thread continues
for(int i=0;i<10;i++) {

System.out.println(Thread.currentThread().getName()+" : "+i);

//this thread halts for 500 millisecond
try {
Thread.sleep(1 * 500);
} catch (InterruptedException e) {
e.printStackTrace();
}

//when counter reaches 5 wait for Other thread to notify it
if(i == 5) {
try {
synchronized(MainThread.class) {
System.out.println("MainThread is Waiting....");
MainThread.class.wait();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}//for
}//main


}