多线程之死锁02

来源:互联网 发布:单片机项目设计教程 编辑:程序博客网 时间:2024/06/18 09:10
class Test implements Runnable{private boolean flag;Test(boolean flag){this.flag = flag;}public void run(){if(flag){while(true){synchronized(MyLock.locka){System.out.println(Thread.currentThread().getName()+"...if locka ");synchronized(MyLock.lockb){System.out.println(Thread.currentThread().getName()+"..if lockb");}}}}else{while(true){synchronized(MyLock.lockb){System.out.println(Thread.currentThread().getName()+"..else lockb");synchronized(MyLock.locka){System.out.println(Thread.currentThread().getName()+".....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();//只是具备了执行资格,处于阻塞状态,并不会立刻处于执行状态,但不一定具有执行权,CPU在不断地切换t2.start();//只是具备了执行资格,但不一定具有执行权,CPU在不断地切换}}

原创粉丝点击