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

Discussion

Sample29 is run - what will be the output?

public class Sample29
{
    static boolean ready = false;

    public static void main(String[] args) throws InterruptedException
    {
        Object lock = new Object();
        new Thread(() ->
        {
            synchronized (lock) { ready = true; lock.notifyAll(); }
        }).start();
        synchronized (lock)
        {
            while (!ready) lock.wait();
        }
        System.out.println("ready");
    }
}

  • A.ready
  • B.The program blocks for ever if the worker notifies first.
  • C.Either ready or a hang, depending on timing
  • D.An IllegalMonitorStateException

Answer: A

The flag is tested inside the lock before waiting, so if the worker has already run, the while loop never waits at all and main proceeds. If it has not, wait releases the lock until the notify arrives. That is precisely why the condition-in-a-loop idiom is immune to the lost wakeup of the previous example.

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

Post your comment

Please log in or register to post a comment.