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


}



AnotherThread.java

/* AnotherThread.java */

public class AnotherThread implements Runnable {

public void run() {
for(int i=0;i<10;i++) { 
System.out.println(Thread.currentThread().getName()+" : "+i);
//this thread halts for 1 second
try {
Thread.sleep(1 * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//Now notify the main thread.
synchronized(MainThread.class) {
System.out.println("AnotherThread Notifying MainThread....");
MainThread.class.notify();
}

}

}


Output



Note : you may get below mentioned error, if you do not add synchronized block before calling wait menthod.

Exception in thread "main" java.lang.IllegalMonitorStateException
                at java.lang.Object.wait(Native Method)
                at java.lang.Object.wait(Object.java:485)
                at test.MainThread.main(MainThread.java:25)

No comments:

Post a Comment