Watch the video of the learning process: [Crazy God Speaks Java]
https://www.bilibili.com/video/BV1V4411p7EF?p=3
Welcome everyone to support Oh, very conscientious teacher!
1. The occurrence of deadlock
Code example:
package com.zjl;
/**
* Created by zjl
* 2020/11/18
**/
public class DeadLock {
public static void main(String[] args) {
Makeup makeup = new Makeup(0, "小红-------");
Makeup makeup1 = new Makeup(1, "小丽-------");
makeup.start();
makeup1.start();
}
}
//口红
class Lipstick{
}
//镜子
class Mirror{
}
class Makeup extends Thread{
//需要的资源只有一份,用static来修饰保证只有一份
static Lipstick lipstick = new Lipstick();
static Mirror mirror = new Mirror();
private int choice; //用来判断选择口红还是镜子
private String girlName; //当前线程的名字
public Makeup(int choice,String girlName){
this.choice = choice;
this.girlName = girlName;
}
@Override
public void run() {
//化妆
try {
makeup();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//化妆,互相持有对方的锁,就是需要拿到对方的资源
public void makeup() throws InterruptedException {
if(choice == 0 ){
synchronized (lipstick){
System.out.println(this.girlName + "获得了口红的锁!!!!");
Thread.sleep(1000);
synchronized (mirror){
System.out.println(this.girlName + "获得了镜子的锁!!!!");
}
}
}else {
synchronized (mirror){
System.out.println(this.girlName + "获得了镜子的锁!!!!");
Thread.sleep(1000);
synchronized (lipstick){
System.out.println(this.girlName + "获得了口红的锁!!!!");
}
}
}
}
}
Test result: the program has been running without stopping
Four necessary conditions for deadlock
Modify the code that caused the deadlock
package com.zjl;
/**
* Created by zjl
* 2020/11/18
**/
public class DeadLock {
public static void main(String[] args) {
Makeup makeup = new Makeup(0, "小红-------");
Makeup makeup1 = new Makeup(1, "小丽-------");
makeup.start();
makeup1.start();
}
}
//口红
class Lipstick{
}
//镜子
class Mirror{
}
class Makeup extends Thread{
//需要的资源只有一份,用static来修饰保证只有一份
static Lipstick lipstick = new Lipstick();
static Mirror mirror = new Mirror();
private int choice; //用来判断选择口红还是镜子
private String girlName; //当前线程的名字
public Makeup(int choice,String girlName){
this.choice = choice;
this.girlName = girlName;
}
@Override
public void run() {
//化妆
try {
makeup();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//化妆,互相持有对方的锁,就是需要拿到对方的资源
public void makeup() throws InterruptedException {
if(choice == 0 ){
synchronized (lipstick){
System.out.println(this.girlName + "获得了口红的锁!!!!");
Thread.sleep(1000);
}
synchronized (mirror){
System.out.println(this.girlName + "获得了镜子的锁!!!!");
}
}else {
synchronized (mirror){
System.out.println(this.girlName + "获得了镜子的锁!!!!");
Thread.sleep(1000);
}
synchronized (lipstick){
System.out.println(this.girlName + "获得了口红的锁!!!!");
}
}
}
}