写一断死锁的java代码
时间: 2024-05-15 22:12:28 浏览: 89
下面是一个简单的 Java 死锁例子:
```java
public class DeadlockDemo {
private static Object lock1 = new Object();
private static Object lock2 = new Object();
public static void main(String[] args) {
Thread t1 = new Thread(new Runnable() {
public void run() {
synchronized(lock1) {
System.out.println("Thread 1: Holding lock 1...");
try {
Thread.sleep(10);
} catch (InterruptedException e) {}
System.out.println("Thread 1: Waiting for lock 2...");
synchronized(lock2) {
System.out.println("Thread 1: Holding lock 1 and lock 2...");
}
}
}
});
Thread t2 = new Thread(new Runnable() {
public void run() {
synchronized(lock2) {
System.out.println("Thread 2: Holding lock 2...");
try {
Thread.sleep(10);
} catch (InterruptedException e) {}
System.out.println("Thread 2: Waiting for lock 1...");
synchronized(lock1) {
System.out.println("Thread 2: Holding lock 1 and lock 2...");
}
}
}
});
t1.start();
t2.start();
}
}
```
在这个例子中,有两个线程分别占用了不同的锁 lock1 和 lock2,但是在执行过程中,它们又都想要获取对方占用的锁。因此,它们就会陷入死锁状态,无法继续执行下去。
阅读全文