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

Discussion

Sample27 is run - what will be the output?

public class Sample27
{
    public static void main(String[] args) throws InterruptedException
    {
        Object lock = new Object();
        Thread t = new Thread(() ->
        {
            synchronized (lock)
            {
                System.out.println("worker");
                lock.notify();
            }
        });
        synchronized (lock)
        {
            t.start();
            lock.wait();
            System.out.println("main");
        }
    }
}

  • A.Either order
  • B.The program blocks for ever.
  • C.worker then main
  • D.main then worker

Answer: C

main holds the lock and calls wait, which releases it and parks main in the wait set, so the worker can enter, print and notify. main then has to re-acquire the monitor, which it can only do after the worker leaves its synchronized block, so its print always comes second.

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

Post your comment

Please log in or register to post a comment.