多个线程占有自己资源还想占用其他线程的资源导致两个或以上线程停止运行的情况
=====
某一个同步块同时拥有“两个以上对象的锁”时可能发生死锁
=====
死锁四个必要条件:
一:
a资源只能被一个进程使用
二:
一个进程阻塞时拥有的a资源不释放
三:
一个进程拥有的a资源在使用完之前不能抢走
四:
一个线程拥有了a资源又想拥有b资源
只要破坏一个或多个条件就能避免死锁
======
package com.wuming.thread; //死锁:多个线程同时抱着对方需要的资源,形成僵持 public class DeadLock {public static void main(String[] args) {Makeup g1 = new Makeup(0,"灰姑凉");Makeup g2 = new Makeup(1,"白雪公主");g1.start();g2.start();} } //口红 class Lipstick{} //镜子 class Mirror{ } class Makeup extends Thread{//需要的资源只有一份,用static来保证只有一份static Lipstick lipstick = new Lipstick();static Mirror mirror = new Mirror();int choice;//选择String girlName;//使用化妆品的人/*** Allocates a new {@code Thread} object. This constructor has the same* effect as {@linkplain #Thread(ThreadGroup, Runnable, String) Thread}* {@code (null, null, gname)}, where {@code gname} is a newly generated* name. Automatically generated names are of the form* {@code "Thread-"+}<i>n</i>, where <i>n</i> is an integer.*/public Makeup(int choice, String girlName) {this.choice = choice;this.girlName = girlName;}@Overridepublic void run() {//化妆try {makeup();} catch (InterruptedException e) {e.printStackTrace();}}//化妆,互相持有对方的锁,就是需要拿到对方的资源private void makeup() throws InterruptedException {if (choice==0){synchronized (lipstick){//获得口红的锁System.out.println(this.girlName+"获得口红的锁");Thread.sleep(1000);//放在这儿会造成死锁/*synchronized (mirror){//一秒钟后想获得镜子System.out.println(this.girlName+"获得镜子的锁");}*/}synchronized (mirror){//一秒钟后想获得镜子System.out.println(this.girlName+"获得镜子的锁");}}else{synchronized (mirror){//获得镜子的锁System.out.println(this.girlName+"获得镜子的锁");Thread.sleep(2000);//放在这儿会造成死锁/*synchronized (lipstick){//两秒中后想获得口红System.out.println(this.girlName+"获得的口红的锁");}*/}synchronized (lipstick){//两秒中后想获得口红System.out.println(this.girlName+"获得的口红的锁");}}}}
白雪公主获得镜子的锁
灰姑凉获得口红的锁
白雪公主获得的口红的锁
灰姑凉获得镜子的锁