0

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?

Thorbjørn Ravn Andersen
  • 73,784
  • 33
  • 194
  • 347
andandandand
  • 21,946
  • 60
  • 170
  • 271
  • 5
    Could you possibly try reading at least half an hour about a certain concept before asking yet another question? – Bozho Dec 13 '09 at 21:59
  • 2
    That's a very interesting suggestion, thanks. You've been most helpful. – andandandand Dec 13 '09 at 22:00
  • 2
    well, I have been helpful, providing you with an answer. Now in return you should take my comments seriously ;) – Bozho Dec 13 '09 at 22:02

5 Answers5

7

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 IV
  • 19,322
  • 3
  • 53
  • 57
6

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
  • 9,828
  • 4
  • 39
  • 39
5

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

David M
  • 71,481
  • 13
  • 158
  • 186
3

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
  • 588,226
  • 146
  • 1,060
  • 1,140
1

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
  • 73,784
  • 33
  • 194
  • 347