死锁
死锁条件
-
1.互斥条件:一个资源只能被一个进程使用
-
2.请求与保持条件:一个进程因请求另外资源被阻塞时,对以获得的锁不释放
-
3.不剥夺条件:进程已经获得的资源,未使用完,不能强行剥夺,
-
4.环路等待:若干进程头尾相接,的循环等待条件
public class DeadLock {
public static void main(String[] args) {
Makeup makeup1=new Makeup(0,"灰姑娘");
Makeup makeup2=new Makeup(1,"公主");
makeup1.start();
makeup2.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+"获得口红的锁");
}
}
//拿出来
// synchronized (lipstick){//一秒后拿口红
// System.out.println(this.girlName+"获得口红的锁");
// }
}
}
}
结果:
灰姑娘获得口红的锁
公主获得镜子的锁
/两个想成都抱着对方的资源,然后僵持,成死锁
解决:
public class DeadLock {
public static void main(String[] args) {
Makeup makeup1=new Makeup(0,"灰姑娘");
Makeup makeup2=new Makeup(1,"公主");
makeup1.start();
makeup2.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+"获得口红的锁");
}
}
//解决办法拿出来
synchronized (lipstick){//一秒后拿口红
System.out.println(this.girlName+"获得口红的锁");
// }
}
}
}
现在就是不在拿到镜子的锁去申请口红,破坏了环路等待条件