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

Discussion

Sample56 is run - what will be the output?

public class Sample56
{
    public static void main(String[] args) throws InterruptedException
    {
        final Object lock = new Object();
        Thread holder = new Thread(() ->
        {
            synchronized (lock)
            {
                try { Thread.sleep(3000); } catch (InterruptedException e) { }
            }
        });
        holder.start();
        Thread.sleep(100);
        Thread waiter = new Thread(() -> { synchronized (lock) { } });
        waiter.start();
        Thread.sleep(100);
        System.out.println(waiter.getState());
        holder.interrupt();
    }
}

  • A.WAITING
  • B.TIMED_WAITING
  • C.NEW
  • D.BLOCKED

Answer: D

The holder keeps the monitor across its sleep, because sleep releases no locks, so the second thread sits at the entrance to the synchronized block. Waiting to acquire a monitor is exactly what BLOCKED means, as distinct from the WAITING that wait() produces.

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

Post your comment

Please log in or register to post a comment.