多线程中死锁的简单理解
package com.mc.DeadThread;
//死锁,多线程抱着对方需要的资源,就形成了死锁
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 + "获得了镜子的锁");
}
}
} else {
synchronized (mirror) {
System.out.println(this.girlname+ "获得了镜子的锁");
Thread.sleep(1000);
synchronized (lipstick) {
System.out.println(this.girlname+ "获得了口红的锁");
}
}
}
}
}