How to use wait()/notify() in Java

jrad picture jrad · Jul 17, 2012 · Viewed 11.7k times · Source

I know that there are a few threads open regarding this topic, but I'm just looking for a VERY ELEMENTARY example of how to use wait() and notify() in Java. By "VERY ELEMENTARY," I mean simply printing something out. Thanks.

EDIT: Here's what I have tried thus far and I get an IllegalMonitorStateException:

public void waiting() {
        for(int i = 0; i < 10; i++) {
            if(i == 5)
                try {
                    this.wait();
                } catch (InterruptedException e) {

                }
            else
                System.out.println(i);
        }
        System.out.println("notify me now");    
        this.notify();
}

Answer

Kumar Vivek Mitra picture Kumar Vivek Mitra · Jul 17, 2012

wait and notify are used in synchronized block while using threads to suspend and resume where left off.

Wait immediately looses the lock, whereas Nofity will leave the lock only when the ending bracket is encountered.

public class Mythread implements Runnable{



public synchronized void goo(){

System.out.println("Before Wait");

wait();

System.out.println("After Wait");


}


public synchronized void foo(){

System.out.println("Before Notify");

notify();

System.out.println("After Notify");

}


public class Test{

public static  void main(String[] args){

Thread t = new Thread(new Mythread);

t.start();

 }
}