浏览 2000 次
锁定老帖子 主题:写死锁的郁闷
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
|
|
---|---|
作者 | 正文 |
发表时间:2008-04-02
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 声明:ITeye文章版权属于作者,受法律保护。没有作者书面许可不得转载。
推荐链接
|
|
返回顶楼 | |
发表时间:2009-03-12
这样改就行: public class TestDeadLock implements Runnable{ int flag ; static Object o1 = new Object(); static Object o2 = new Object(); TestDeadLock(int i) { this.flag=i; } 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(1); TestDeadLock test2 = new TestDeadLock(2); Thread t1 = new Thread(test1); Thread t2 = new Thread(test2); t1.start(); t2.start(); } }
|
|
返回顶楼 | |