Java死锁的简单例子
两个线程互相占有对方需要的资源而不释放,便形成了死锁。
代码如下:
Program.java
/**
* 程序类
* @author michael
*
*/
public class Program implements Runnable {
//两个静态的资源
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();
}
}
控制台结果: