package com.example.demo.thread;
/**
* @projectName: demo
* @package: com.example.demo.thread
* @className: TestDeath
* @author:
* @description: 測試死鎖:多個線程互相擁有相同的資源會出現(xiàn)死鎖現(xiàn)象
* @date: 2021/12/8 14:56
*/
public class TestDeath {
public static void main(String[] args) {
MakeUp zmakeUp = new MakeUp(1, "張三");
MakeUp lmakeUp = new MakeUp(0, "李三");
new Thread(zmakeUp).start();
new Thread(lmakeUp).start();
}
}
class MakeUp implements Runnable {
// static在創(chuàng)建對象前初始化百拓,保證唯一性
static Lipstick lipstick = new Lipstick();
static Mirror mirror = new Mirror();
int choose;
String personName;
public MakeUp(int choose, String personName) {
this.choose = choose;
this.personName = personName;
}
@Override
public void run() {
if (choose == 0) {
synchronized (lipstick) {
System.out.println(personName + ":先使用口紅化妝");
System.out.println("口紅哈希" + lipstick.hashCode());
try {
Thread.sleep(1000);
synchronized (mirror) {
System.out.println(personName + ":再使用鏡子化妝");
System.out.println("鏡子哈希" + mirror.hashCode());
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
} else {
synchronized (mirror) {
System.out.println(personName + ":再使用鏡子化妝");
System.out.println("鏡子哈希" + mirror.hashCode());
try {
Thread.sleep(1000);
synchronized (lipstick) {
System.out.println(personName + ":先使用口紅化妝");
System.out.println("口紅哈希" + lipstick.hashCode());
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
class Lipstick {
}
class Mirror {
}
上面樣例解決方案
synchronized不要嵌套使用
package com.example.demo.thread;
/**
* @projectName: demo
* @package: com.example.demo.thread
* @className: TestDeath
* @author:
* @description: 測試死鎖:synchronized塊中不要出現(xiàn)另一個synchronized塊
* @date: 2021/12/8 14:56
*/
public class TestDeath {
public static void main(String[] args) {
MakeUp zmakeUp = new MakeUp(1, "張三");
MakeUp lmakeUp = new MakeUp(0, "李三");
new Thread(zmakeUp).start();
new Thread(lmakeUp).start();
}
}
class MakeUp implements Runnable {
// static在創(chuàng)建對象前初始化渠鸽,保證唯一性
static Lipstick lipstick = new Lipstick();
static Mirror mirror = new Mirror();
int choose;
String personName;
public MakeUp(int choose, String personName) {
this.choose = choose;
this.personName = personName;
}
@Override
public void run() {
if (choose == 0) {
synchronized (lipstick) {
System.out.println(personName + ":先使用口紅化妝");
System.out.println("口紅哈希" + lipstick.hashCode());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (mirror) {
System.out.println(personName + ":再使用鏡子化妝");
System.out.println("鏡子哈希" + mirror.hashCode());
}
}
} else {
synchronized (mirror) {
System.out.println(personName + ":再使用鏡子化妝");
System.out.println("鏡子哈希" + mirror.hashCode());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
synchronized (lipstick) {
System.out.println(personName + ":先使用口紅化妝");
System.out.println("口紅哈希" + lipstick.hashCode());
}
}
}
}
class Lipstick {
}
class Mirror {
}