死锁的实例

死锁的代码:

package com.et.java.thread;


public class DeadLockTest extends Thread{
static Object obj1=new Object();
static Object obj2=new Object();
int flag;
public DeadLockTest(){};
public DeadLockTest(String name){
super(name);
}
@Override
public void run() {
if(flag==1){
synchronized (obj1) {
System.out.println("拿到了红苹果,还需要拿到青苹果");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (obj2) {
System.out.println("拿到了青苹果");
}
}
}else if(flag==2){
synchronized (obj2) {
System.out.println("拿到了青苹果,还需要拿到红苹果");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (obj1) {
System.out.println("拿到了红苹果");
}
}
}
}
public static void main(String[] args) {
DeadLockTest dlt1=new DeadLockTest("dlt1");
dlt1.flag=1;
DeadLockTest dlt2=new DeadLockTest("dlt2");
dlt2.flag=2;
dlt1.start();
dlt2.start();
}


}

posted @ 2016-07-14 15:17  人间值得  阅读(114)  评论(0编辑  收藏  举报