Java多线程--死锁例子
生活随笔
收集整理的這篇文章主要介紹了
Java多线程--死锁例子
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
package qzy.thread.deadLock;/*** @描述模擬死鎖** 形成死鎖的四個必要條件是什么** 1.互斥條件:線程(進程)對于所分配到的資源具有排它性,即一個資源只能被一個線程(進程)占用,直到被該線程(進程)釋放* 2.請求與保持條件:一個線程(進程)因請求被占用資源而發生阻塞時,對已獲得的資源保持不放。* 3.不剝奪條件:線程(進程)已獲得的資源在末使用完之前不能被其他線程強行剝奪,只有自己使用完畢后才釋放資源。* 4.循環等待條件:當發生死鎖時,所等待的線程(進程)必定會形成一個環路(類似于死循環),造成永久阻塞*** @創建人 joy_qiu* @創建時間 * @修改人和其它信息*/
public class DeadLockDemo {private static Object o1 = new Object();private static Object o2 = new Object();public static void main(String[] args) {new Thread(() -> {synchronized (o1){System.out.println(Thread.currentThread()+":獲取到o1的鎖");try{Thread.sleep(2000);} catch (InterruptedException e) {e.printStackTrace();}System.out.println(Thread.currentThread()+":等待獲取o2的鎖");synchronized (o2){System.out.println(Thread.currentThread()+":獲取到o2的鎖");}}},"線程1").start();new Thread(() -> {synchronized (o2){System.out.println(Thread.currentThread()+":獲取到o2的鎖");try{Thread.sleep(2000);} catch (InterruptedException e) {e.printStackTrace();}System.out.println(Thread.currentThread()+":等待獲取o1的鎖");synchronized (o1){System.out.println(Thread.currentThread()+":獲取到o1的鎖");}}},"線程2").start();}
}/*** 解決死鎖的例子*/
class UnDeadLock{private static Object o1 = new Object();private static Object o2 = new Object();public static void main(String[] args) {new Thread(() -> {synchronized (o1){System.out.println(Thread.currentThread()+":獲取到o1的鎖");try{Thread.sleep(2000);} catch (InterruptedException e) {e.printStackTrace();}System.out.println(Thread.currentThread()+":等待獲取o2的鎖");synchronized (o2){System.out.println(Thread.currentThread()+":獲取到o2的鎖");}}},"線程1").start();new Thread(() -> {synchronized (o1){System.out.println(Thread.currentThread()+":獲取到o1的鎖");try{Thread.sleep(2000);} catch (InterruptedException e) {e.printStackTrace();}System.out.println(Thread.currentThread()+":等待獲取o2的鎖");synchronized (o2){System.out.println(Thread.currentThread()+":獲取到o2的鎖");}}},"線程2").start();}
}
總結
以上是生活随笔為你收集整理的Java多线程--死锁例子的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python三维图能画地图_Python
- 下一篇: vue 手机端路由切换滑动_vue移动端