死锁
死锁
产生死锁的四个必要条件
- 互斥条件:一个资源每次只能被一个进程使用
- 请求与保持条件:一个进程因请求资源而阻塞时,对已获得的资源保持不放
- 不剥夺条件:进程已获得的资源在未使用完之前,不能强行剥夺
- 循环等待条件:若干进程之间形成一种头尾相接的循环等待资源关系
死锁示例
package com.example.multi_thread;
public class TestLock {
public static void main(String[] args) {
Makeup makeup = new Makeup("灰姑娘", 0);
Makeup makeup1 = new Makeup("白雪公主", 1);
new Thread(makeup).start();
new Thread(makeup1).start();
}
}
class Mirror {
}
class Lipstick {
}
class Makeup implements Runnable {
static Mirror mirror = new Mirror();
static Lipstick lipstick = new Lipstick();
private String name;
private int choose;
public Makeup(String name, int choose) {
this.name = name;
this.choose = choose;
}
@Override
public void run() {
try {
makeup();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private void makeup() throws InterruptedException {
if (choose == 0) {
synchronized (mirror) {
System.out.println(Thread.currentThread().getName() + "获取镜子");
Thread.sleep(100);
synchronized (lipstick) {
System.out.println(Thread.currentThread().getName() + "获取口红");
}
}
} else {
synchronized (lipstick) {
System.out.println(Thread.currentThread().getName() + "获取口红");
Thread.sleep(100);
synchronized (mirror) {
System.out.println(Thread.currentThread().getName() + "获取镜子");
}
}
}
}
}
输出:
Thread-0获取镜子
Thread-1获取口红
修复后:
package com.example.multi_thread;
public class TestLock {
public static void main(String[] args) {
Makeup makeup = new Makeup("灰姑娘", 0);
Makeup makeup1 = new Makeup("白雪公主", 1);
new Thread(makeup).start();
new Thread(makeup1).start();
}
}
class Mirror {
}
class Lipstick {
}
class Makeup implements Runnable {
static Mirror mirror = new Mirror();
static Lipstick lipstick = new Lipstick();
private String name;
private int choose;
public Makeup(String name, int choose) {
this.name = name;
this.choose = choose;
}
@Override
public void run() {
try {
makeup();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private void makeup() throws InterruptedException {
if (choose == 0) {
synchronized (mirror) {
System.out.println(Thread.currentThread().getName() + "获取镜子");
Thread.sleep(100);
}
synchronized (lipstick) {
System.out.println(Thread.currentThread().getName() + "获取口红");
}
} else {
synchronized (lipstick) {
System.out.println(Thread.currentThread().getName() + "获取口红");
Thread.sleep(100);
}
synchronized (mirror) {
System.out.println(Thread.currentThread().getName() + "获取镜子");
}
}
}
}
输出:
Thread-0获取镜子
Thread-1获取口红
Thread-1获取镜子
Thread-0获取口红