java多线程 模拟死锁程序

public class TestDeadLock implements Runnable{
	public int flag = 1;
	public static Object o1 = new Object();
	public static Object o2 = new Object();
	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();

	}

	@Override
	public void run() {
		System.out.println("flag:"+flag);
		if(flag==1){
			synchronized(o1){
				try {
					Thread.sleep(500);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				synchronized(o2){
					System.out.println("1");
				}
			}
			
		}
		else if(flag == 0){
			synchronized(o2){
				try {
					Thread.sleep(500);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				synchronized(o1){
					System.out.println("0");
				}
			}
			
		}
		
	}

}


posted @ 2013-03-29 13:38  xinyuyuanm  阅读(220)  评论(0编辑  收藏  举报