04_多线程_死锁

来源:互联网 发布:献给虚无的供物 知乎 编辑:程序博客网 时间:2024/06/05 02:15

一、售票中的死锁

*死锁。同步中嵌套同步。产生死锁的原因:同步中嵌套同步,锁却不同A线程持有a锁,线程B持有b锁,两个线程都持有锁,且互不相让,不释放锁,就会死锁现实中的例子,两个一人拿一根筷子吃饭,一人轮流吃一口就和谐了死锁也有和谐状态()*/class Ticket implements Runnable{private  int tick = 1000;Object obj = new Object();boolean flag = true;public  void run(){if(flag){while(true){synchronized(obj){show();}}}elsewhile(true)show();}public synchronized void show()//this{synchronized(obj){if(tick>0){try{Thread.sleep(10);}catch(Exception e){}System.out.println(Thread.currentThread().getName()+"....code : "+ tick--);}}}}class  DeadLockDemo{public static void main(String[] args) {Ticket t = new Ticket();Thread t1 = new Thread(t);Thread t2 = new Thread(t);t1.start();try{Thread.sleep(10);}catch(Exception e){}t.flag = false;t2.start();}}

运行结果 :


死锁。 程序挂在那里不动了

/*死锁。 程序挂在那里不动了同步中嵌套同步。*/class TestDeadLock implements Runnable{private boolean flag;TestDeadLock(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 TestDeadLock(true));Thread t2 = new Thread(new TestDeadLock(false));t1.start();t2.start();}}
运行结果:



0 0