java写一个多线程死锁的代码
时间: 2024-09-10 17:26:54 浏览: 53
Java多线程死锁示例
在 Java 中,死锁通常发生在两个或更多的线程相互等待对方释放资源的情况下。这里是一个简单的示例,展示了如何编写可能会导致死锁的多线程代码:
```java
public class DeadLockExample {
private final Object lockA = new Object();
private final Object lockB = new Object();
public void threadOne() {
synchronized (lockA) {
System.out.println("Thread One acquired lock A");
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
// 死锁:尝试获取无法立即获得的锁
synchronized (lockB) {
System.out.println("Thread One acquired lock B");
}
}
}
public void threadTwo() {
synchronized (lockB) {
System.out.println("Thread Two acquired lock B");
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
// 死锁:尝试获取无法立即获得的锁
synchronized (lockA) {
System.out.println("Thread Two acquired lock A");
}
}
}
public static void main(String[] args) {
DeadLockExample example = new DeadLockExample();
new Thread(example::threadOne).start();
new Thread(example::threadTwo).start();
}
}
阅读全文