1

Please let me know how I can print “After wait”; how can I notify main thread in the following code:

import java.util.*;  

public class Test {

      public static void main(String[] args) throws InterruptedException {
            ArrayList al = new ArrayList(6);
            al.add(0, "abc");
        al.add(1, "abc");
        al.add(2, "abc");
        synchronized(al){
            System.out.println("Before wait");
            al.wait();
            System.out.println("After wait");
        }       

      }

}
Kai
  • 38,985
  • 14
  • 88
  • 103
Gaurav Navgire
  • 780
  • 5
  • 17
  • 29

2 Answers2

4

The wait() call is blocking until someone notify()s it... Basically, you would need to create a new thread that calls al.notify() when the main thread is blocking in wait().

This program prints Before wait, pauses for one second, and prints After wait.

import java.util.ArrayList;

public class Test {

    public static void main(String[] args) throws InterruptedException {

        final ArrayList al = new ArrayList(6);
        al.add(0, "abc");
        al.add(1, "abc");
        al.add(2, "abc");

        // Start a thread that notifies al after one second.
        new Thread() {
            public void run() {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                synchronized (al) {
                    al.notify();      // <-- this "releases" the wait.
                }
            }
        }.start();

        synchronized (al) {
            System.out.println("Before wait");
            al.wait();
            System.out.println("After wait");
        }
    }
}

Here is a link to one of my previous answers, explaining why wait() and notify() must be executed while holding the lock of the monitor.

Community
  • 1
  • 1
aioobe
  • 413,195
  • 112
  • 811
  • 826
2

You're not creating any other threads, so it's hard to see how there is anything else to notify the main thread. However, if you did have another thread which had a reference to al, you'd use something like:

synchronized(al) {
    al.notify();
}

or

synchronized(al) {
    al.notifyAll();
}

(The difference between the two is that notify will only wake a single thread from waiting; notifyAll will wake all the threads waiting on that object.)

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194