public class MultiLockExample {
private Object lock1 = new Object();
private Object lock2 = new Object();
public void method1() throws InterruptedException {
synchronized (lock1) {
System.out.println("进入方法1");
// 线程在获取lock1锁后,进入阻塞状态并等待100毫秒
// Thread.sleep(100);
// 线程尝试获取lock2锁
synchronized (lock2) {
System.out.println("执行方法1");
lock2.notify();
}
}
}
public void method2() throws InterruptedException {
synchronized (lock2) {
System.out.println("进入方法2");
lock2.wait();
// 线程尝试获取lock1锁
synchronized (lock1) {
System.out.println("执行方法2");
}
}
}
public static void main(String[] args) {
MultiLockExample example = new MultiLockExample();
Thread thread1 = new Thread(() -> {
try {
example.method1();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
});
Thread thread2 = new Thread(() -> {
try {
example.method2();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
});
thread1.start();
thread2.start();
}
}
标签:synchronized,Thread,案例,System,lock2,嵌套,lock1,new
From: https://www.cnblogs.com/jishaling/p/17695583.html