public class DeadlockTest {
Object o1 = new Object();
Object o2 = new Object();
void test01() {
synchronized (o1) {
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
// 执行test02需要拿到o2的锁
System.out.println(Thread.currentThread().getName()+"等待锁定o2对象");
test02();
}
}
void test02() {
synchronized (o2) {
// 执行test01需要拿到o1的锁
System.out.println(Thread.currentThread().getName()+"等待锁定o1对象");
test01();
}
}
public static void main(String[] args) throws InterruptedException {
DeadlockTest deadlock = new DeadlockTest();
new Thread(deadlock::test01, "thread-1").start();
TimeUnit.MILLISECONDS.sleep(10);
new Thread(deadlock::test02, "thread-2").start();
}
}
模拟死锁
最新推荐文章于 2024-07-28 21:21:15 发布