- class Test implements Runnable
- {
- boolean flag=true;
- private int i=1;
- Test(boolean f){
- this.flag=f;
- }
- public void run(){
- if(this.flag){
- while(i>0){
- System.out.println(" "+i+++" "+Thread.currentThread().getName()+":我准备进入锁A");
- synchronized(MyLock.locka){
- System.out.println(" "+i+++" "+Thread.currentThread().getName()+":我关闭了锁A,下面准备进入锁B");
-
- synchronized(MyLock.lockb){
- System.out.println(" "+i+++" "+Thread.currentThread().getName()+":在进入锁A后,我又进入了锁B,现在锁A和锁B都被我关了哦");
- System.out.println(" "+i+++" "+Thread.currentThread().getName()+":运行完成,现在打开锁B");
- }
- System.out.println(" "+i+++" "+Thread.currentThread().getName()+":运行完成,现在打开锁A");
- }
-
- }
- }else{
- while(i>0){
- System.out.println(" "+i+++" "+Thread.currentThread().getName()+":我准备进入锁B");
- synchronized(MyLock.lockb){
- System.out.println(" "+i+++" "+Thread.currentThread().getName()+":我关闭了锁B,下面准备进入锁A");
-
- synchronized(MyLock.locka){
- System.out.println(" "+i+++" "+Thread.currentThread().getName()+":在进入锁B后,我又进入了锁A,现在锁B和锁A都被我关了哦");
- System.out.println(" "+i+++" "+Thread.currentThread().getName()+":运行完成,现在打开锁A");
- }
- System.out.println(" "+i+++" "+Thread.currentThread().getName()+":运行完成,现在打开锁B");
- }
- }
- }
- }
- }
- class MyLock
- {
- static Object locka = new Object();
- static Object lockb = new Object();
- }
- class DeadLockTest
- {
- public static void main(String[] args)
- {
- Test t = new Test(true);
- Thread t1 = new Thread(t);
- Thread t2 = new Thread(t);
- t1.start();
- try{Thread.sleep(10);}catch(Exception e){}
- t.flag = false;
- t2.start();
- }
- }
复制代码 |