Java死鎖的簡單例子
兩個線程互相占有對方需要的資源而不釋放,便形成了死鎖匠题。
代碼如下:
Program.java
/**
* 程序類
* @author michael
*
*/
public class Program implements Runnable {
//兩個靜態(tài)的資源
public static Object obj1 = new Object();
public static Object obj2 = new Object();
//標志位
public int flag = 1; //1 or 2
@Override
public void run() {
if(flag == 1) {
synchronized (obj1) {
System.out.println("flag: " + flag + ", 鎖住了資源obj1");
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("flag: " + flag + ", 等待獲取資源obj2");
synchronized (obj2) {
System.out.println("flag: " + flag + ", 獲得資源obj2");
}
}
} else if(flag == 2) {
synchronized (obj2) {
System.out.println("flag: " + flag + ", 鎖住了資源obj2");
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("flag: " + flag + ", 等待獲取資源obj1");
synchronized (obj1) {
System.out.println("flag: " + flag + ", 獲得資源obj1");
}
}
}
}
}
DeadLock.java
DeadLock.java
/**
* 死鎖測試.
* @author michael
*
*/
public class DeadLock {
public static void main(String[] args) {
Program p1 = new Program();
Program p2 = new Program();
p1.flag = 1;
p2.flag = 2;
new Thread(p1).start();
new Thread(p2).start();
}
}
控制臺結果: