views:

162

answers:

5

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?

+5  A: 

You only have one thread. wait() is waiting for a notify from another thread.

David M
+3  A: 

Since no other thread notifies the object's monitor you are waiting on, it is just blocking there. And since you are synchronizing and waiting on a local variable, hardly any other thread would be able to call notify() on it.

Bozho
Thanks, this has saved me time (and provided content for others to learn). Nice going, man.
omgzor
+4  A: 

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.

Francis Upton
+4  A: 

wait and notifyAll are for multithreading. args.wait() will wait forever until some other thread calls args.notifyAll() or args.notify().

When you call args.wait(100), it is waiting for 100ms, timing out, and continuing.

If you are familiar with semaphores, that is basically what wait/notify are.

karoberts
+1  A: 

From http://java.sun.com/docs/books/tutorial/essential/concurrency/guardmeth.html

When wait is invoked, the thread releases the lock and suspends execution. At some future time, another thread will acquire the same lock and invoke Object.notifyAll, informing all threads waiting on that lock that something important has happened:

The Java Tutorial is an excellent learning resource.

Thorbjørn Ravn Andersen