java基础知识回顾之java Thread类学习(七)--java多线程安全问题(死锁)
生活随笔
收集整理的這篇文章主要介紹了
java基础知识回顾之java Thread类学习(七)--java多线程安全问题(死锁)
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
死鎖:是兩個(gè)或者兩個(gè)以上的線(xiàn)程被無(wú)限的阻塞,線(xiàn)程之間互相等待所需資源。
線(xiàn)程死鎖產(chǎn)生的條件:
- 當(dāng)兩個(gè)線(xiàn)程相互調(diào)用Join()方法。
- 當(dāng)兩個(gè)線(xiàn)程使用嵌套的同步代碼塊的時(shí)候,一個(gè)線(xiàn)程占用了另一個(gè)線(xiàn)程的鎖,互相等待阻塞,就有可能產(chǎn)生死鎖。
下面看代碼:
代碼1:死鎖的案例
package com.lp.ecjtu.Thread;/* 死鎖:常見(jiàn)情景之一:同步的嵌套。*/ class Ticket implements Runnable {private int num = 100;Object obj = new Object();boolean flag = true;public void run(){if(flag)while(true){synchronized(obj)//同步代碼塊里面調(diào)用同步函數(shù) {show();}}elsewhile(true)this.show();}public synchronized void show()//同步函數(shù)里面的調(diào)用同步代碼塊 {synchronized(obj){if(num>0){try{Thread.sleep(10);}catch (InterruptedException e){}System.out.println(Thread.currentThread().getName()+".....sale...."+num--);}}} }public class DeathLockThread1 {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(InterruptedException e){}t.flag = false;t2.start();} }代碼2:
?
package com.lp.ecjtu.Thread;class DeathLockRunable implements Runnable{private boolean flag;public DeathLockRunable(boolean flag){this.flag = flag;}@Overridepublic void run() {if(flag){synchronized (Lock.mylock1){System.out.println("if mylock1"+Thread.currentThread().getName());synchronized (Lock.mylock2){System.out.println("if mylock2"+Thread.currentThread().getName());}}}else{synchronized (Lock.mylock2){System.out.println("else mylock2"+Thread.currentThread().getName());synchronized (Lock.mylock1){System.out.println("else mylock1"+Thread.currentThread().getName());}}}}}class Lock{static Object mylock1 = new Object();static Object mylock2 = new Object();}public class DeathLockThread{public static void main(String[] args){Thread t1 = new Thread(new DeathLockRunable(true));Thread t2 = new Thread(new DeathLockRunable(false));t1.start();t2.start();}}輸出結(jié)果:if mylock1Thread-0
else mylock2Thread-1
?
總結(jié)
以上是生活随笔為你收集整理的java基础知识回顾之java Thread类学习(七)--java多线程安全问题(死锁)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: ubuntu完全卸载apache2
- 下一篇: 图标之家