java编写经典死锁示例代码
时间: 2023-09-29 14:06:12 浏览: 88
java 一个死锁的例子
5星 · 资源好评率100%
以下是一个简单的Java死锁示例代码:
```java
public class DeadlockExample {
private static Object lock1 = new Object();
private static Object lock2 = new Object();
public static void main(String[] args) {
Thread thread1 = new Thread(new Runnable() {
public void run() {
synchronized (lock1) {
System.out.println("Thread 1 acquired lock1");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (lock2) {
System.out.println("Thread 1 acquired lock2");
}
}
}
});
Thread thread2 = new Thread(new Runnable() {
public void run() {
synchronized (lock2) {
System.out.println("Thread 2 acquired lock2");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (lock1) {
System.out.println("Thread 2 acquired lock1");
}
}
}
});
thread1.start();
thread2.start();
}
}
```
这个代码创建了两个线程,每个线程都会获取一个锁并尝试获取另一个锁。如果这两个线程在短时间内并发运行,它们可能会彼此等待对方释放锁,从而导致死锁。
阅读全文