Java多线程05_死锁
public class DeadLock {
public static void main(String
[] args
) {
Makeup girl1
= new Makeup(0, "女一号");
Makeup girl2
= new Makeup(1, "女二号");
girl1
.start();
girl2
.start();
}
}
class Lipstick{
}
class Mirror{
}
class Makeup extends Thread{
static Lipstick lipstick
= new Lipstick();
static Mirror mirror
= new Mirror();
int choice
;
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();
}
}
private 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(2000);
synchronized (lipstick
) {
System
.out
.println(this.girlName
+"获得了口红");
}
}
}
}
}
程序死锁:
女二号获得了镜子
女一号获得了口红
产生死锁的四个必要条件(只要破坏其中一个条件就可以避免死锁):
互斥条件: 一个资源每次只能被一个进程使用
请求与保持条件: 一个资源因请求资源受阻,对已获得的资源保持不放
不剥夺条件: 进程已获得的资源,在未使用完之前不能强行剥夺
循环等待条件: 若干进程之间形成一种头尾相接的循环等待资源关系
修改代码:
private 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(2000);
}
synchronized (lipstick
) {
System
.out
.println(this.girlName
+"获得了口红");
}
}
}
死锁问题解决:
女一号获得了口红
女二号获得了镜子
女一号获得了镜子
女二号获得了口红