java多线程死锁实例
时间: 2023-12-06 14:38:50 浏览: 91
以下是一个Java多线程死锁的实例:
```java
public class DeadLock implements Runnable {
private boolean flag;
private static Object o1 = new Object();
private static Object o2 = new Object();
public DeadLock(boolean flag) {
this.flag = flag;
}
@Override
public void run() {
if (flag) {
synchronized (o1) {
System.out.println(Thread.currentThread().getName() + "获取了o1锁");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (o2) {
System.out.println(Thread.currentThread().getName() + "获取了o2锁");
}
}
} else {
synchronized (o2) {
System.out.println(Thread.currentThread().getName() + "获取了o2锁");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (o1) {
System.out.println(Thread.currentThread().getName() + "获取了o1锁");
}
}
}
}
}
public class DeadLockTest {
public static void main(String[] args) {
Thread t1 = new Thread(new DeadLock(true), "线程1");
Thread t2 = new Thread(new DeadLock(false), "线程2");
t1.start();
t2.start();
}
}
```
上述代码中,两个线程分别获取o1和o2锁,但是获取锁的顺序不同,导致两个线程互相等待对方释放锁,从而形成死锁。
阅读全文