- class Test implements Runnable
- {
-
- private boolean flag;
- Test(boolean flag)
- {
- this.flag=flag;
- }
- public void run()
- {
- if(flag)
- {
- while(true)
- {
- synchronized(Lock.Locka)
- {
- System.out.println("if locka");
- synchronized(Lock.Lockb)
- {
- System.out.println("if lockb");
- }
- }
- }
- }
- else
- {
- while(true)
- {
- synchronized(Lock.Lockb)
- {
- System.out.println("else lockb");
- synchronized(Lock.Locka)
- {
- System.out.println("else locka");
- }
- }
- }
- }
- }
- }
- class Lock
- {
- static Object Locka=new Object();
- static Object Lockb=new Object();
- }
- class DeadLockDemo1
- {
- public static void main(String[] args)
- {
- Thread t1=new Thread(new Test(true));
- Thread t2=new Thread(new Test(false));
- t1.start();
- t2.start();
- }
- }
-
复制代码
这段是可以实现死锁的,下面这段是有问题的,请帮忙分析一下区别
- class Test implements Runnable
- {
- Object Locka=new Object();
- Object Lockb=new Object();
- private boolean flag;
- Test(boolean flag)
- {
- this.flag=flag;
- }
- public void run()
- {
- if(flag)
- {
- while(true)
- {
- synchronized(Locka)
- {
- System.out.println("if locka");
- synchronized(Lockb)
- {
- System.out.println("if lockb");
- }
- }
- }
- }
- else
- {
- while(true)
- {
- synchronized(Lockb)
- {
- System.out.println("else lockb");
- synchronized(Locka)
- {
- System.out.println("else locka");
- }
- }
- }
- }
- }
- }
- class Demo1
- {
- public static void main(String[] args)
- {
- Thread t1=new Thread(new Test(true));
- Thread t2=new Thread(new Test(false));
- t1.start();
- t2.start();
- }
- }
-
复制代码 |