举一个java死锁的例子
时间: 2023-05-23 12:01:01 浏览: 107
一个经典的 Java 死锁例子是当两个或多个线程彼此持有对方所需的锁时。例如,当线程 A 拥有锁 L1,并且试图获取锁 L2 时,但在同一时间,线程 B 拥有锁 L2,并且试图获取锁 L1。这个情况下,两个线程将永远等待,产生死锁。以下是一个简单的 Java 代码示例:
```
class DeadlockExample {
Object lock1 = new Object();
Object lock2 = new Object();
Thread thread1 = new Thread(new Runnable() {
@Override
public void run() {
synchronized (lock1) {
System.out.println("Thread1: Holding lock1...");
try { Thread.sleep(10); }
catch (InterruptedException e) {}
System.out.println("Thread1: Waiting for lock2...");
synchronized (lock2) {
System.out.println("Thread1: Holding lock1 and lock2...");
}
}
}
});
Thread thread2 = new Thread(new Runnable() {
@Override
public void run() {
synchronized (lock2) {
System.out.println("Thread2: Holding lock2...");
try { Thread.sleep(10); }
catch (InterruptedException e) {}
System.out.println("Thread2: Waiting for lock1...");
synchronized (lock1) {
System.out.println("Thread2: Holding lock1 and lock2...");
}
}
}
});
public static void main(String[] args) {
DeadlockExample dle = new DeadlockExample();
dle.thread1.start();
dle.thread2.start();
}
}
```
在这个例子中,两个线程分别拥有 lock1 和 lock2,但是他们都试图获取对方的锁,从而导致了死锁。
阅读全文