java死锁代码示例
时间: 2023-07-02 07:15:52 浏览: 113
下面是一个简单的Java死锁代码示例:
```java
public class DeadlockExample {
private final Object lock1 = new Object();
private final Object lock2 = new Object();
public void method1() {
synchronized (lock1) {
System.out.println("Method 1 acquired lock1");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (lock2) {
System.out.println("Method 1 acquired lock2");
}
}
}
public void method2() {
synchronized (lock2) {
System.out.println("Method 2 acquired lock2");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (lock1) {
System.out.println("Method 2 acquired lock1");
}
}
}
public static void main(String[] args) {
DeadlockExample example = new DeadlockExample();
Thread thread1 = new Thread(() -> example.method1());
Thread thread2 = new Thread(() -> example.method2());
thread1.start();
thread2.start();
}
}
```
在上面的代码中,有两个线程分别执行`method1`和`method2`方法。每个方法都需要获得两个锁才能执行,但是它们的锁顺序不同,这就导致了死锁的可能性。如果`thread1`获得了`lock1`,然后`thread2`获得了`lock2`,那么它们就会互相等待对方释放锁,从而进入死锁状态。
阅读全文