日期:2014-05-20 浏览次数:20777 次
public class TestDeadLock implements Runnable{ public int flag = 0; public static Object o1 =new Object(); public static Object o2 = new Object(); public static void main(String[] args) { TestDeadLock t = new TestDeadLock(); TestDeadLock tt = new TestDeadLock(); t.flag = 0; tt.flag = 1; Thread t1 = new Thread(t); Thread t2 = new Thread(tt); t1.start(); t2.start(); } public void run() { System.out.println("flag ="+ flag); if (flag == 1) { synchronized(o1){ try { Thread.sleep(1000); }catch(InterruptedException e) { System.out.println("fail!"); } } synchronized(o2) { System.out.println("thread1 is close!"); } } else { synchronized(o2){ try{ Thread.sleep(5000); }catch(InterruptedException e) { System.out.println("fail!"); } } synchronized(o1) { System.out.println("thread2 is close!"); } } } }