Java 死锁例子

来源:互联网 发布:moto g4 plus4g网络 编辑:程序博客网 时间:2024/06/08 05:33
/*死锁:产生死锁的原因之一 同步的嵌套本应该无限打印 但死锁会停止打印*/class Test implements Runnable{ boolean flag=true;Test(boolean flag) {this.flag=flag;}public void run(){if(flag){while(true){synchronized(MyLock.locka){System.out.println("if----locka");synchronized(MyLock.lockb){System.out.println("if----lockb");}}}}else{while(true){synchronized(MyLock.lockb){System.out.println("else----lockb");synchronized(MyLock.locka){System.out.println("else----locka");}}}}}}class MyLock{public static final Object locka=new Object();public static final Object lockb=new Object();}class DeadLockTest{public static void main(String[] args) {Test a=new Test(true);Thread t1=new Thread(a);Thread t2=new Thread(a);t1.start(); try{                      Thread.sleep(100);                  }                  catch(InterruptedException e){                    }                a.flag=false;t2.start();}}

原创粉丝点击