死锁
死锁
-
当多个线程各自占有一些资源,并且互相等待对方占有的资源时会出现死锁的问题。比如说线程A和线程B都需要拿到金锁和银锁才能继续执行,线程A先拿金锁再拿银锁,线程B先拿银锁再拿金锁,这样可能导致线程A拿到金锁,线程B拿到银锁,都在等待对方手中的锁,导致程序无法继续运行,就导致了死锁的问题。
-
死锁有四个必要条件
-
互斥条件:一个资源每次只能被一个进程使用。
-
请求与保持条件:一个进程因请求资源而阻塞时,对已获得的资源保持不放。
-
不可剥夺条件:进程已获得的资源,在未使用之前,不能强行剥夺。
-
循环等待条件:若干进程之间形成一种首尾相接的循环等待资源关系。
-
代码演示
package MultiProcess;
public class DeadBlock {
public static void main(String[] args) {
Rob r1 = new Rob(0, "尔康");
Rob r2 = new Rob(1, "五阿哥");
r1.start();
r2.start();
}
}
class GoldBlock{}
class SilverBlock{}
class Rob extends Thread{
static GoldBlock goldBlock = new GoldBlock();
static SilverBlock silverBlock = new SilverBlock();
int choice;
String name;
Rob(int choice, String name){
this.choice = choice;
this.name = name;
}
@Override
public void run() {
try {
rob();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//互相持有对方的资源
private void rob() throws InterruptedException{
if(choice == 0){
synchronized (goldBlock){
System.out.println(this.name + "抢到金锁");
Thread.sleep(1000);
synchronized (silverBlock){
System.out.println(this.name + "抢到银锁");
}
}
}else{
synchronized (silverBlock){
System.out.println(this.name + "抢到银锁");
Thread.sleep(1000);
synchronized (goldBlock){
System.out.println(this.name + "抢到金锁");
}
}
}
}
}
结果
尔康抢到金锁
五阿哥抢到银锁