Java DeadLock

public class TestDeadLock implements Runnable{
	public int flag = 1;
	static Object o1 = new Object(),o2 = new Object();
	public void run(){
		System.out.println("flag = "+flag);
		if(flag==1){
			synchronized(o1){
				try{
					Thread.sleep(500);	//o1 sleeps so that t2 can lock o2;
				}catch(Exception e){
					e.printStackTrace();
				}
				synchronized(o2){	
					System.out.println("11");//can't print;

				}
			}
		}
		if(flag ==0){
			synchronized(o2){   // t2 Locks o2
				try{
					Thread.sleep(5000);
				}catch(Exception e){
					e.printStackTrace();
				}
				synchronized(o1){
					System.out.println("00");//can't print;
				}
			}
		}
	}
public static void main(String[] args){

	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();
	t2.start();
}
}

结果:flag = 1
     flag = 0
    -(程序不会终止,因为双方都在各自等待对方解锁)							    s

你可能感兴趣的:(Java DeadLock)