今天写了个程序想出现一个死锁,具体代码是:
public class TestDeadLock implements Runnable{
/**
* @param args
*/
public int flag = 2;
static Object o1 = new Object();
static Object o2 = new Object();
public void run(){
if(flag == 1){
synchronized(o1){
System.out.println("锁住o1");
try {
Thread.sleep(5000);
}catch(Exception e){}
}
synchronized(o2){
System.out.println("1");
}
}
//疑问:无法死锁
if(flag == 0){
synchronized(o2){
System.out.println("锁住o2");
try {
Thread.sleep(5000);
}catch(Exception e){}
}
synchronized(o1){
System.out.println("2");
}
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
TestDeadLock td1 = new TestDeadLock();
TestDeadLock td2 = new TestDeadLock();
td1.flag = 1;
td2.flag = 0;
Thread t1 = new Thread(td1);
Thread t2 = new Thread(td2);
t1.start();
try {
Thread.sleep(5000);
} catch (Exception e) {
// TODO: handle exception
}
t2.start();
}
}
但是运行的结果没有出现死锁,代码该如何修改才能有死锁呢???求解决!!!
|