I also had the same problem yesterday and I wrote an example program to understand this . Hope this helps you.
Suppose we have two threads .First thread is started and is in run(). It calls the second thread and it is in run now. If u want
thread1 to wait() until thread2 sends notify() , this is what u could do.
Program 1: Thread1.java
class Thread1 extends Thread {
/** Overwrite the method from java.lang.Thread */
public void run() {
System.out.println("Thread1.run()");
try{
for(;;) {
String status = "P";
// pass "this" object to thread 2.
new Thread2(status,this).start();
// thread1 now waits until it gets notify from thread2
waitmethod();
}
}
catch (Exception e){
System.out.println("Caught exception in Thread1" + e.toString());
}
}
public void waitmethod(){
try{
synchronized(this) {
System.out.println("Waiting");
wait();
}
}
catch (Exception e){
System.out.println("Caught exception in waitmethod" + e.toString());
}
}
public void notifymethod() {
try{
synchronized(this) {
System.out.println("Notifying");
notifyAll();
}
}
catch (Exception e){
System.out.println("Caught exception in notifymethod" + e.toString());
}
}
}
Program2: Thread2.java
class Thread2 extends Thread {
private String _status;
private Thread2 _ch;
public void run() {
System.out.println("Iam in Thread2.run() ");
_status = "C";
System.out.println(_status);
// once thread2 is done , it gets synchronized lock on // thread1 and calls thread1's notifymethod
synchronized(_ch) {
_ch.notifymethod();
}
// now u are back to Thread1 to iterate next time.
}
public Thread2(String status,Thread1 ch) {
_status = status;
_ch = ch;
}
}
Hope this makes u understand wait() and notifyall() methods.