deadlock
- When a synchronized code block holds "locks on more than two objects" at the same time, a "deadlock" problem may occur
- Deadlock: Multiple threads hold each other's resources and form a deadlock
Four conditions for deadlock
- Mutual exclusion condition: a resource can only be used by one process at a time
- Request and hold conditions: When a process is blocked by requesting resources, it will hold on to the acquired resources
- No deprivation condition: The resource that the process has obtained cannot be forcibly deprived before it is used up
- Circular waiting condition: A cyclic waiting resource relationship is formed between several processes.
The four necessary conditions for deadlock are listed above. We can avoid deadlock as long as we find a way to destroy any one or more of them.
package com.thread;
public class DeadLock {
public static void main(String[] args) {
Makeup g1 = new Makeup(0,"灰姑娘");
Makeup g2 = new Makeup(1,"白雪公主");
new Thread(g1).start();
new Thread(g2).start();
}
}
// 口红
class Lipstick{
}
// 镜子
class Mirror{
}
class Makeup implements Runnable{
// 需要的资源只要一份,用static来保持只有一份
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 + "获得镜子的锁");
// }
}
// 解决方法,将锁放入外面,通过释放上一个锁来获取下一个锁
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 + "获得口红的锁");
}
}
}
}