死锁

/*
* 若o1,o2同时被锁定,
* 则执行···
*
* */
public class deadLock implements Runnable{

/**
* @param args
*/
private int flag = 0 ;
static Object o1= new Object(),o2 = new Object();//注意:static 否则的话就不是死锁;因为static 变量是静态变量
deadLock(int flag){
this.flag = flag;
}
public static void main(String[] args) {
deadLock dead1 = new deadLock(0);
deadLock dead2 = new deadLock(1);
Thread thread1 = new Thread(dead1);
Thread thread2 = new Thread(dead2);
thread1.start();
thread2.start();
}

@Override
public void run() {
System.out.println("flag:"+flag);// TODO Auto-generated method stub
if(flag==0){
synchronized(o1){
try {
Thread.sleep(500);//sleep时不放开锁;
}catch(InterruptedException e){
System.out.println(" o1休眠被打断。。。");
}
synchronized(o2){
System.out.println("o2也被锁定");
}//end synchronized(o2)
}//end synchronized(o1)
}//end if;
if(flag == 1){
synchronized(o2){
try {
Thread.sleep(500);
}catch(InterruptedException e){
System.out.println("o2休眠被打断。。");
}
synchronized(o1){
System.out.println("o1也别锁定");
}//end synchronized(o1);
}//end synchronized(o2)
}// end if
}//end run();

}

你可能感兴趣的:(死锁)