Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package multithreading.nested_monitor_lockout;
- public class SomeObject {
- private final Object monitor = new Object();
- public void foo1() throws InterruptedException {
- System.out.println(Thread.currentThread().getName() + " enters foo1()");
- synchronized(this) {
- System.out.println(Thread.currentThread().getName() + " locks this");
- synchronized (monitor) {
- System.out.println(Thread.currentThread().getName() + " locks monitor");
- System.out.println(Thread.currentThread().getName() + " calls monitor.wait() and releases monitor");
- monitor.wait(); // after calling curr thread releases lock on a monitor object
- }
- }
- }
- public void foo2() {
- System.out.println(Thread.currentThread().getName() + " enters foo2()");
- synchronized (this) {
- System.out.println(Thread.currentThread().getName() + " locks this");
- synchronized (monitor) {
- System.out.println(Thread.currentThread().getName() + " locks monitor");
- monitor.notify();
- System.out.println(Thread.currentThread().getName() + " calls monitor.notify() and releases monitor");
- }
- }
- }
- }
- public class Client {
- public static void main(String[] args) throws InterruptedException {
- SomeObject someObject = new SomeObject();
- new Thread(() -> {
- try {
- someObject.foo1();
- } catch (InterruptedException e) {
- throw new RuntimeException(e);
- }
- }, "ThreadA").start();
- Thread.sleep(3000); // needed to run ThreadA earlier than ThreadB
- new Thread(() -> someObject.foo2(), "ThreadB").start();
- }
- }
Add Comment
Please, Sign In to add comment