用Java语言生成一段死锁代码
时间: 2023-06-01 10:05:04 浏览: 106
java 一个死锁的例子
5星 · 资源好评率100%
以下是一段可能导致死锁的Java代码示例:
```java
public class DeadlockExample {
private static final Object lock1 = new Object();
private static final Object lock2 = new Object();
public static void main(String[] args) {
Thread thread1 = new Thread(new Runnable() {
@Override
public void run() {
synchronized (lock1) {
System.out.println("Thread 1 acquired lock1");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (lock2) {
System.out.println("Thread 1 acquired lock2");
}
}
}
});
Thread thread2 = new Thread(new Runnable() {
@Override
public void run() {
synchronized (lock2) {
System.out.println("Thread 2 acquired lock2");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (lock1) {
System.out.println("Thread 2 acquired lock1");
}
}
}
});
thread1.start();
thread2.start();
}
}
```
这个程序创建了两个线程,每个线程都试图获得两个对象锁(lock1和lock2),但是获取锁的顺序不同,这可能导致死锁。如果线程1先获得了lock1并等待获取lock2,同时线程2先获得了lock2并等待获取lock1,那么就会发生死锁。
阅读全文