java死锁样例
package bin.io.thread;
/**测试死锁
* @author 牵手无奈
* date:2015-9-1
*
*/
public class DeadLock implements Runnable{
private int flag = 0;
private static Object o1 = new Object();
private static Object o2 = new Object();
public int getFlag() {
return flag;
}
public void setFlag(int flag) {
this.flag = flag;
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
DeadLock d1 = new DeadLock();
DeadLock d2 = new DeadLock();
d1.setFlag(0);
d2.setFlag(1);
new Thread(d1).start();
new Thread(d2).start();
}
@Override
public void run() {
if(flag==0){
synchronized (o1) {
System.out.println("我锁定O1,然后睡上1秒!");
try {
Thread.sleep(1000);
System.out.println("我o1睡醒了,要准备拿o2");
synchronized (o2) {
System.out.println("我拿到o2,,表示没有发生死锁");
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}else if(flag==1){
synchronized (o2) {
System.out.println("我锁定O2,然后睡上1秒!");
try {
Thread.sleep(1000);
System.out.println("我o2睡醒了,要准备拿o1");
synchronized (o1) {
System.out.println("我拿到o1,表示没有发生死锁");
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
运行结果
我锁定O2,然后睡上1秒!
我锁定O1,然后睡上1秒!
我睡醒了,要准备拿o1
我睡醒了,要准备拿o2