写一段JAVA代码,通过实现runnable接口来模拟死锁的过程
时间: 2024-10-20 21:07:09 浏览: 15
在Java中,我们可以创建两个线程,它们各自持有对方需要的对象资源,然后尝试同时获取另一个对象的锁,这就可能导致死锁。以下是一个简单的示例代码来模拟这个过程:
```java
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
class ResourceA {
private final ReentrantLock lock = new ReentrantLock();
private final Condition condition = lock.newCondition();
public void lockResource() throws InterruptedException {
lock.lock();
try {
System.out.println(Thread.currentThread().getName() + " acquired lock on Resource A");
condition.await(); // 模拟等待另一个资源
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
public void releaseResource() {
lock.unlock();
System.out.println(Thread.currentThread().getName() + " released lock on Resource A");
}
}
class ResourceB {
private final ReentrantLock lock = new ReentrantLock();
private final Condition condition = lock.newCondition();
public void lockResource(ResourceA a) throws InterruptedException {
lock.lock();
try {
System.out.println(Thread.currentThread().getName() + " acquired lock on Resource B");
a.condition.signal(); // 模拟唤醒另一个线程
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
public void releaseResource() {
lock.unlock();
System.out.println(Thread.currentThread().getName() + " released lock on Resource B");
}
}
public class DeadlockSimulation implements Runnable {
private final ResourceA resourceA = new ResourceA();
private final ResourceB resourceB = new ResourceB();
@Override
public void run() {
try {
Thread t1 = new Thread(() -> {
resourceB.lockResource(resourceA);
resourceA.lockResource(); // 这里可能会导致死锁
}, "Thread 1");
Thread t2 = new Thread(() -> {
resourceA.lockResource(resourceB);
resourceB.lockResource(); // 这里也可能会导致死锁
}, "Thread 2");
t1.start();
t2.start();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
new DeadlockSimulation().run();
}
}
```
在这个例子中,两个线程都试图先获取到另一个资源的锁,如果顺序不对,就会陷入死锁状态,因为每个线程都在等待对方释放它不需要的锁。
阅读全文