package suo;
public class DeadLockTest implements Runnable{
private int flag;
static Object o1 = new Object(), o2 = new Object(); //靜態的對象,被DeadLockTest的所有實例對象所公用
public void run(){
System.out.println(flag);
if(flag == 0){
synchronized(o1){
try{
Thread.sleep(500);
} catch(Exception e){
e.printStackTrace();
}
synchronized(o2){
}
}
}
if(flag == 1){
synchronized(o2){
try{
Thread.sleep(500);
} catch(Exception e){
e.printStackTrace();
}
synchronized(o1){
}
}
}
}
public static void main(String[] args){
DeadLockTest test1 = new DeadLockTest();
DeadLockTest test2 = new DeadLockTest();
test1.flag = 1;
test2.flag = 0;
Thread thread1 = new Thread(test1);
Thread thread2 = new Thread(test2);
thread1.start();
thread2.start();
}
}
/*
解釋:在main方法中,實例化了兩個實現了Runnable接口的DeadLockTest對象test1和test2,
test1的flag等於1,所以在thread1線程執行的時候執行的是run()方法後半部分的代碼,
test2的flag等於2,所以在thread2線程啓動的時候執行的是run()方法前半部分的代碼,此時,
出現了下列現象:thread1線程佔有了o1對象並等待o2對象,而thread2線程佔有了o2對象並等待o1對象,
而o1和o2又被這倆個線程所共享,所以就出現了死鎖的問題了。*/
java製造死鎖
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.