<span style="font-size:14px;">package thread;
public class TestDeadLock implements Runnable{
public int flag = 1;
static Object o1 = new Object(),o2 = new Object();
@Override
public void run() {
System.out.println("flag:"+flag);
if(flag==1){
synchronized(o1){
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
synchronized(o2){
System.out.println("我是o2,被锁住了");
}
}
}
if(flag==0){
synchronized(o2){
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
synchronized(o1){
System.out.println("我是o1,被锁住了");
}
}
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
TestDeadLock d1 = new TestDeadLock();
TestDeadLock d2 = new TestDeadLock();
Thread t1 = new Thread(d1);
Thread t2 = new Thread(d2);
d1.flag = 1;
d2.flag = 0;
t1.start();
t2.start();
}
}
</span>
运行结果为
flag:1
flag:0由于发生死锁,两条if语句中的打印语句永远都不会执行