写死锁的郁闷

这段时间在看马士兵老师的关于线程同步的教程,完了自己想写一个死锁出来,按照马老师的精髓,我写了下面的代码,但我无论如何也没法将它锁死,下面是代码希望大家帮忙看下是什么原因,我感谢万分!!!!(jdK版本:6.0)
package cn.zhangxuemin.j2se;

public class TestDeadLock implements Runnable{
	static int flag  ;
	static Object o1 = new Object();
	static Object o2 = new Object();
	public void run () {
		System.out.println("flag= "+flag);
		if(flag==2) {
			synchronized (o1) {
				System.out.println("i am object 1");
				try {
					Thread.sleep(500);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				
				synchronized (o2) {
					System.out.println("i am object 2");
				}
			}
		}
		if(flag==1) {
			synchronized (o2) {
				System.out.println("i am object 222");
				try {
					Thread.sleep(500);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				synchronized (o1) {
					System.out.println("i am object 111");
				}
			}
		}
	}
	
	public static void main(String[] args) {
		TestDeadLock test1 = new TestDeadLock();
		TestDeadLock test2 = new TestDeadLock();
		
		
		Thread t1 = new Thread(test1);
		Thread t2 = new Thread(test2);
		flag = 1;
		t1.start();
		flag = 2;
		t2.start();
	}
	
}


运行结果:
flag= 2
i am object 1
flag= 2
i am object 2
i am object 1
i am object 2

你可能感兴趣的:(jdk,thread,J2SE)