线程死锁:多个线程互相抱着对方需要的资源,然后形成僵持
避免产生死锁的条件
死锁代码:
线程死锁:多个线程互相抱着对方需要的资源,然后形成僵持
@Override
public void run() {
makeup();
}
public void makeup(){
if (choice == 0){
synchronized (lipstick){
System.out.println(this.grilname+"拿到口红");
//同步持有对方锁
synchronized (mirror){
System.out.println(this.grilname+"拿到镜子");
}
}
}else {
synchronized (mirror){
System.out.println(this.grilname+"拿到镜子");
synchronized (lipstick){
System.out.println(this.grilname+"拿到口红");
}
}
}
}
解决:把同时持有对方资源,放在外面同步
@Override
public void run() {
makeup();
}
public void makeup(){
if (choice == 0){
synchronized (lipstick){
System.out.println(this.grilname+"拿到口红");
}
synchronized (mirror){
System.out.println(this.grilname+"拿到镜子");
}
}else {
synchronized (mirror){
System.out.println(this.grilname+"拿到镜子");
}
synchronized (lipstick){
System.out.println(this.grilname+"拿到口红");
}
}
}
关于Lock锁
lock锁与synchronized 对比