使⽤Java编写一个线程死锁的例子
时间: 2024-09-09 13:08:38 浏览: 50
在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 t1 = new Thread(new Runnable() {
@Override
public void run() {
synchronized (lock1) {
System.out.println("Thread 1: Locked lock1");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (lock2) {
System.out.println("Thread 1: Locked lock2");
}
}
}
});
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
synchronized (lock2) {
System.out.println("Thread 2: Locked lock2");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (lock1) {
System.out.println("Thread 2: Locked lock1");
}
}
}
});
t1.start();
t2.start();
}
}
```
在这个例子中,有两个锁对象`lock1`和`lock2`,以及两个线程`t1`和`t2`。每个线程都首先获取一个锁,然后休眠一段时间,之后尝试获取另一个线程持有的锁。如果`t1`线程首先获取了`lock1`,而`t2`线程获取了`lock2`,那么这两个线程将会等待对方释放锁,从而导致死锁。
阅读全文