死锁
作者:互联网
化妆的例子
两个女生同时要化妆,需要用口红和镜子:
-
当女孩1拿到口红时,1秒后需要拿到镜子,才能解除对口红的锁(即:同步块中嵌套类一个同步块)
-
同一时间下女孩2拿到镜子,2秒后需要拿到口红才能解除对镜子的锁
-
因此两方僵持住了,形成了死锁
package test2;
public class DeadLock {
public static void main(String[] args) {
Makeup g1=new Makeup(0,"girl1");
Makeup g2=new Makeup(1,"gilr2");
g1.start();
g2.start();
}
}
//口红
class LipStick{
}
//镜子
class Mirror{
}
//化妆
class Makeup extends Thread{
//需要的资源只有一个,用static保证只有一份
static LipStick lipStick=new LipStick();
static Mirror mirror=new Mirror();
int choice;
String girlName;
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(this.choice==0){
synchronized (lipStick){
System.out.println(this.girlName+"获得口红的锁");
sleep(1000);
synchronized (mirror){
System.out.println(this.girlName+"获得镜子的锁");
}
}
}else{
synchronized (mirror){
System.out.println(this.girlName+"获得镜子的锁");
sleep(2000);
synchronized (lipStick){
System.out.println(this.girlName+"获得口红的锁");
}
}
}
}
}
修改代码,使其不会死锁:把嵌套的代码块分离
private void makeup() throws InterruptedException {
if(this.choice==0){
synchronized (lipStick){
System.out.println(this.girlName+"获得口红的锁");
sleep(1000);
}
synchronized (mirror){
System.out.println(this.girlName+"获得镜子的锁");
}
}else{
synchronized (mirror){
System.out.println(this.girlName+"获得镜子的锁");
sleep(2000);
}
synchronized (lipStick){
System.out.println(this.girlName+"获得口红的锁");
}
}
}
标签:girlName,synchronized,口红,System,死锁,println,out 来源: https://www.cnblogs.com/kakafa/p/15001855.html