学习过程观看视频:[狂神说Java]
https://www.bilibili.com/video/BV1V4411p7EF?p=3
欢迎大家支持噢,很良心的老师了!
1、死锁的产生
代码示例:
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 + "获得了口红的锁!!!!");
}
}
}
}
}
测试结果:程序一直在运行,没有停止
产生死锁的四个必要条件
修改产生死锁的代码
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 + "获得了口红的锁!!!!");
}
}
}
}