Java并发问题:死锁案例分析
死锁是Java并发编程中一个常见的问题。它发生在两个或更多进程互相等待对方释放资源的情况,此时所有进程都无法继续。
以下是一个经典的死锁案例:
// 进程A持有资源1,需要资源2
class ProcessA implements Runnable {
Resource1 r1;
Resource2 r2;
public ProcessA(Resource1 r1, Resource2 r2) {
this.r1 = r1;
this.r2 = r2;
}
@Override
public void run() {
// 执行需要资源2的代码
while (r2.isAvailable()) {
// 释放资源1,等待资源2
r1.release();
try {
// 等待资源2可用
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// 执行需要资源1的代码
while (r1.isAvailable()) {
r1.acquire();
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
// 进程B持有资源2,需要资源1
class ProcessB implements Runnable {
Resource2 r2;
Resource1 r1;
public ProcessB(Resource2 r2, Resource1 r1) {
this.r2 = r2;
this.r1 = r1;
}
@Override
public void run() {
while (r1.isAvailable()) {
r1.acquire();
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
// 执行需要资源2的代码,释放资源1
r2.release();
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
while (r2.isAvailable()) {
r2.acquire();
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
// 执行需要资源1的代码,释放资源2
r1.release();
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
在这个例子中,ProcessA
持有Resource1
和需要Resource2
,而ProcessB
持有Resource2
和需要Resource1
。
当两个进程都等待对方释放资源时(如ProcessA
等待Resource2
可用,ProcessB
等待Resource1
可用),就形成了死锁。
还没有评论,来说两句吧...