死锁模拟
编程模型
-
化妆需要镜子,口红
-
两个人分别拿到镜子和口红,谁都不让谁,都想拿到对方手里的资源
-
就造成了死锁的问题
程序一直处于等待状态
package cn.usts.edu.lesson07;
/**
* 编程模型
* 化妆需要镜子,口红
* 两个人分别拿到镜子和口红,谁都不让谁,都想拿到对方手里的资源
* 就造成了死锁的问题
*
* 解决方案:
* 不能拿对方的锁
*
*
* */
public class DeadLock {
public static void main(String[] args) {
MakeUp makeUp1 = new MakeUp(0,"白雪公主");
MakeUp makeUp2 = new MakeUp(1,"灰姑娘");
new Thread(makeUp1).start();
new Thread(makeUp2).start();
}
}
// 口红
class Lipstick{
}
// 镜子
class Mirror{
}
// 化妆
class MakeUp implements Runnable {
// 资源只有一份,用static修饰
static final Lipstick lipstick = new Lipstick();
static final Mirror mirror = new Mirror();
int choice;
String name;
MakeUp(int choice,String name){
// choice = 0;先拿镜子,
// choice = 1;先拿口红
this.choice = choice;
this.name = name;
}
private void makeup() throws InterruptedException {
if (choice==0){
synchronized (lipstick){
System.out.println(name+"拿到了口红,上了锁,别人不许用,还想要镜子");
Thread.sleep(1000);
synchronized (mirror){
System.out.println(name+"拿到了镜子的锁,别人不许用,现在我都拿到,化完妆了");
}
}
}else {
synchronized (mirror){
System.out.println(name+"拿到了镜子,上了锁,别人不许用,还想要口红");
Thread.sleep(2000);
synchronized (lipstick){
System.out.println(name+"拿到了口红的锁,别人不许用,现在我都拿到,化完妆了");
}
}
}
}
@Override
public void run() {
try {
makeup();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
解决方案
依次获取资源, 一个目标不能同时拿到两个把锁
package cn.usts.edu.lesson07;
/**
* 编程模型
* 化妆需要镜子,口红
* 两个人分别拿到镜子和口红,谁都不让谁,都想拿到对方手里的资源
* 就造成了死锁的问题
*
* 解决方案:
* 不能拿对方的锁
*
*
* */
public class DeadLock {
public static void main(String[] args) {
MakeUp makeUp1 = new MakeUp(0,"白雪公主");
MakeUp makeUp2 = new MakeUp(1,"灰姑娘");
new Thread(makeUp1).start();
new Thread(makeUp2).start();
}
}
// 口红
class Lipstick{
}
// 镜子
class Mirror{
}
// 化妆
class MakeUp implements Runnable {
// 资源只有一份,用static修饰
static final Lipstick lipstick = new Lipstick();
static final Mirror mirror = new Mirror();
int choice;
String name;
MakeUp(int choice,String name){
// choice = 0;先拿镜子,
// choice = 1;先拿口红
this.choice = choice;
this.name = name;
}
private void makeup() throws InterruptedException {
if (choice==0){
synchronized (lipstick){
System.out.println(name+"拿到了口红,上了锁");
Thread.sleep(5000);
}
System.out.println(name+"口红使用完了,我还想用镜子");
synchronized (mirror){
System.out.println(name+"拿到了镜子,上了锁,我口红和镜子都用完了.化完妆了");
}
}
else {
synchronized (mirror){
System.out.println(name+"拿到了镜子,上了锁,还想要口红");
Thread.sleep(7000);
}
System.out.println(name+"镜子使用完了,我还想用口红");
synchronized (lipstick){
System.out.println(name+"拿到了口红的锁,别人不许用,我口红和镜子都用完了,化完妆了");
}
}
}
@Override
public void run() {
try {
makeup();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}