Search code examples
javamultithreadingwaitscjp

Understanding wait()


I created this silly program to play with wait()

public class WaitTest {
    public static void main(String [] args) {

      System.out.print("1 ");
      synchronized(args){

        System.out.print("2 ");

        try {
          args.wait();
          args.notifyAll();
        }
        catch(InterruptedException e){ System.out.print("exception caught");}

        System.out.print("3 ");
      }
   }
}

On my machine, the code never gets to print 3, unless I write wait(100) or another number of milliseconds. Why is this?


Solution

  • You are doing the wait() before the notifyAll(). wait() is going to block. When you put the timeout value in, wait() will timeout and then your program will continue. If you want your program to work, create a thread and do your notifyAll() there. wait() and notifyAll are designed for interthread synchronization.