日期:2014-05-20 浏览次数:20732 次
public class TestDeadLock implements Runnable{ public int flag = 2; static Object o1 = new Object(); static Object o2 = new Object(); public void run(){ if(flag == 1){ synchronized(o1){ System.out.println("锁住o1"); try { Thread.sleep(5000); }catch(Exception e){} } synchronized(o2){ System.out.println("1"); } } //疑问:无法死锁 if(flag == 0){ synchronized(o2){ System.out.println("锁住o2"); try { Thread.sleep(5000); }catch(Exception e){} } synchronized(o1){ System.out.println("2"); } } } 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(); } }
public class TestDeadLock implements Runnable{ public int flag = 2; static Object o1 = new Object(); static Object o2 = new Object(); public void run(){ if(flag == 1){ synchronized(o1){ System.out.println("锁住o1"); try { Thread.sleep(5000); }catch(Exception e){} synchronized(o2){ System.out.println("1"); } } } //疑问:无法死锁 if(flag == 0){ synchronized(o2){ System.out.println("锁住o2"); try { Thread.sleep(5000); }catch(Exception e){} synchronized(o1){ System.out.println("2"); } } } } 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(); } }
------解决方案--------------------
顶1 楼的,LZ你的代码,把第二个sychronized 放在外面,这样的话,就不是用sychronized code(同步代码块),用sychronized method(同步函数)来解决,我们平常,写代码,是为了不让其死锁!
------解决方案--------------------