死鎖問題
什么是死鎖?
死鎖是指兩個或兩個以上的行程在執行程序中,由于競爭資源或者由于彼此通信而造成的一種阻塞的現象,若無外力作用,它們都將無法推進下去,
比如現在A有倚天劍,B有屠龍刀,A想要B的屠龍刀,B想要A的倚天劍,但是A不想把倚天劍給B,B同樣也不想把屠龍刀給A,
兩個人都等著對方把武器交出來...于是就形成了死鎖,
public class DeadLock {
public static void main(String[] args) {
new Thread(new T("滅絕師太",1)).start();
new Thread(new T("金毛獅王",0)).start();
}
}
class Yitianjian{
}
class Tulongdao{
}
class T implements Runnable{
static Yitianjian yitianjian = new Yitianjian();
static Tulongdao tulongdao = new Tulongdao();
private String name;
private int flog;
T(String name, int flog){
this.flog = flog;
this.name = name;
}
@Override
public void run() {
if(flog == 1){
synchronized (yitianjian){
System.out.println(this.name + "獲得倚天劍");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (tulongdao){
System.out.println(this.name + "獲得屠龍刀");
}
}
}else{
synchronized (tulongdao){
System.out.println(this.name + "獲得屠龍刀");
synchronized (yitianjian){
System.out.println(this.name + "獲得倚天劍");
}
}
}
}
}
運行結果:

現在兩個人都等著對方把武器交出來, 程式就一直卡住了,
產生死鎖的4個必要條件
- 互斥條件:一個資源每次只能被一個行程使用,
- 請求與保持條件:一個行程因請求資源而阻塞時,對以獲得的資源保持不放,
- 不剝奪條件:行程以獲得的資源,在未使用完之前,不能強行剝奪,
- 回圈等待條件:若干行程之間形成一種頭尾相接的回圈等待資源關系,
如何避免死鎖
只要行程不滿足以上四個條件的一個或多個就可以避免死鎖,
public class DeadLock {
public static void main(String[] args) {
new Thread(new T("滅絕師太",1)).start();
new Thread(new T("金毛獅王",0)).start();
}
}
class Yitianjian{
}
class Tulongdao{
}
class T implements Runnable{
static Yitianjian yitianjian = new Yitianjian();
static Tulongdao tulongdao = new Tulongdao();
private String name;
private int flog;
T(String name, int flog){
this.flog = flog;
this.name = name;
}
@Override
public void run() {
if(flog == 1){
synchronized (yitianjian){
System.out.println(this.name + "獲得倚天劍");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
synchronized (tulongdao){
System.out.println(this.name + "獲得屠龍刀");
}
}else{
synchronized (tulongdao){
System.out.println(this.name + "獲得屠龍刀");
}
synchronized (yitianjian){
System.out.println(this.name + "獲得倚天劍");
}
}
}
}
運行結果:

現在兩個人都獲得了自己想要的武器了,
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/193598.html
標籤:Java
