java死锁

来源:互联网 发布:我的凉山兄弟 知乎 编辑:程序博客网 时间:2024/05/16 22:35
//该例子会产生死锁class Test implements Runnable{private boolean flag;Test(boolean flag){this.flag = flag;}public void run(){if(flag){synchronized(MyLock.locka){System.out.println("if locka");synchronized(MyLock.lockb){System.out.println("if lockb");}}}else{synchronized(MyLock.lockb){System.out.println("else lockb");synchronized(MyLock.locka){System.out.println("else locka");}}}}}class MyLock{static Object locka = new Object();static Object lockb = new Object();}class DeadLockTest{public static void main(String[] args){Thread t1 = new Thread(new Test(true));Thread t2 = new Thread(new Test(false));t1.start();t2.start();}}

原创粉丝点击