Java并发编程:死锁示例解析
死锁是多线程编程中的一种严重问题,当两个或更多的线程在执行过程中因争夺资源而造成的一种互相等待的现象称为死锁。
下面是一个经典的死锁示例:
// 定义资源
class Resource {
private int count;
public Resource(int count) {
this.count = count;
}
// 获取资源,计数减1
public synchronized void acquire() {
if (count == 0) throw new RuntimeException("Resource exhausted");
count--;
}
// 释放资源,计数加1
public synchronized void release() {
count++;
// 检查是否有循环等待(死锁)
if (count > resourceCount) throw new RuntimeException("Deadlock detected");
}
// 获取当前资源总数
public int getCount() {
return count;
}
private int resourceCount; // 全部资源数量
}
// 定义线程
class ThreadA extends Thread {
Resource resource1 = new Resource(5);
ThreadA() {
start();
}
@Override
public void run() {
resource1.acquire(); // 获取第一个资源
try {
Thread.sleep(1000); // 暂停执行,模拟等待资源
} catch (InterruptedException e) {
e.printStackTrace();
}
resource1.release(); // 释放第一个资源
}
}
class ThreadB extends Thread {
Resource resource2 = new Resource(5);
ThreadB() {
start();
}
@Override
public void run() {
resource2.acquire(); // 获取第二个资源
try {
Thread.sleep(1000); // 暂停执行,模拟等待资源
} catch (InterruptedException e) {
e.printStackTrace();
}
resource2.release(); // 释放第二个资源
}
}
public class Main {
public static void main(String[] args) {
Resource resourceCount = 5; // 全部资源数量
ThreadA threadA = new ThreadA();
ThreadB threadB = new ThreadB();
threadA.start();
threadB.start();
try {
threadA.join();
threadB.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
// 检查是否存在循环等待(死锁)
if (resourceCount != resource1.getCount() + resource2.getCount()) {
System.out.println("Deadlock detected");
} else {
System.out.println("No deadlock detected");
}
}
}
在这个示例中,两个线程(ThreadA和ThreadB)分别获取了资源1和资源2。线程A在获取资源后休眠一段时间,然后释放资源。同理,线程B也是这样操作的。
如果线程等待时间过长或者出现其他情况导致循环等待(死锁),则程序会输出”Deadlock detected”。否则,输出”No deadlock detected”。
还没有评论,来说两句吧...