开发者

A query regarding Java Threads

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");
        }       

      }

}


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.

  • Why must wait() always be in synchronized block


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.)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜