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

Discussion

Sample36 is run - what will be the output?

public class Sample36
{
    static class Vault
    {
        synchronized void hold() throws InterruptedException
        {
            Thread.sleep(200);
            System.out.print("held ");
        }

        synchronized void peek() { System.out.print("peeked "); }
    }

    public static void main(String[] args) throws InterruptedException
    {
        Vault v = new Vault();
        Thread a = new Thread(() -> { try { v.hold(); } catch (InterruptedException e) { } });
        a.start();
        Thread.sleep(50);
        v.peek();
        a.join();
    }
}

  • A.peeked held
  • B.Either order
  • C.An IllegalMonitorStateException from peek()
  • D.held peeked

Answer: D

sleep does not release any monitor, so the worker keeps the lock on the Vault for the whole 200 milliseconds. main wakes after 50 and blocks at peek until the worker has printed and left its synchronized method. Using wait(200) instead would release the lock and reverse the order.

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

Post your comment

Please log in or register to post a comment.