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();
}
}
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.
Examination Categories
- SSC Exams
- Banking Exams
- Teaching Exams
- Civil Services Exams
- Railways Exams
- Engineering Recruitment Exams
- Defence Exams
- State Government Exams
- Police Exams
- Insurance Exams
- Nursing Exams
- Other Government Exams
- NRA CET
- PG Entrance Exams
- Campus Placement
- MBA Entrance Exams
- CUET and UG Entrance
- Judiciary Exams
- Regulatory Body Exams
- Software Development