Machine-translated by Google. Questions are authored in English.
Top

Discussion

Sample28 is run - what will be the output?

public class Sample28 extends Thread
{
    static final Object GATE = new Object();

    public void run()
    {
        synchronized (GATE)
        {
            GATE.notifyAll();
        }
    }

    public static void main(String[] args) throws InterruptedException
    {
        Sample28 signaller = new Sample28();
        signaller.start();
        signaller.join();

        synchronized (GATE)
        {
            GATE.wait();
        }
        System.out.println("woken");
    }
}

  • A.woken, because the notification is remembered until a thread waits.
  • B.woken, after a default timeout of one second.
  • C.An IllegalMonitorStateException from the wait() call.
  • D.The program blocks for ever, because the notify was sent before the wait.

Answer: D

A monitor keeps no record of notifications. The join guarantees the worker has already notified and died before main waits, so the signal is gone and nothing will ever wake main. This lost-wakeup is why the condition must be tested inside the lock before waiting at all.

No comment is present. Be the first to comment.
Loading…

Post your comment

Please log in or register to post a comment.