本篇是学习死锁的知识,例子是化妆场景,只有一份镜子和口红,A先得到口红,再想要镜子;B先拿了镜子还想要口红;如果不先释放自己手中的物品的锁时,就会造成相互僵持的场景,造成死锁现象。
package lesson04;
//死锁:化妆
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 name;
//有参构造器
Makeup(int choice, String name) {
this.choice = choice;
this.name = name;
}
@Override
public void run() {
makeup();
}
private void makeup() {
if (choice == 0) {
//只有在得到镜子的锁以后,才会释放口红的锁
synchronized (lipstick){//拿到口红的锁
System.out.println(this.name+"拿到了口红的锁");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (mirror){
System.out.println(this.name+"拿到了镜子的锁");//一秒后想要拿镜子的锁
}
}
}else {
//只有得到口红的锁以后,才会释放镜子的锁
synchronized (mirror){
System.out.println(this.name+"拿到了镜子的锁");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (lipstick){
System.out.println(this.name+"拿到了口红的锁");
}
}
}
}
}
运行结果:
package lesson04;
//死锁:化妆
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 name;
//有参构造器
Makeup(int choice, String name) {
this.choice = choice;
this.name = name;
}
@Override
public void run() {
makeup();
}
private void makeup() {
if (choice == 0) {
synchronized (lipstick){//拿到口红的锁
System.out.println(this.name+"拿到了口红的锁");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
synchronized (mirror){
System.out.println(this.name+"拿到了镜子的锁");//一秒后想要拿镜子的锁
}
}else {
synchronized (mirror){
System.out.println(this.name+"拿到了镜子的锁");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
synchronized (lipstick){
System.out.println(this.name+"拿到了口红的锁");
}
}
}
}
运行结果: