发生死锁的情况:多个线程需要同时占用多个共享资源而发生需要互相死循环等待的情况
public class Mirror { //镜子 }
public class Lipstick { //口红 }
线程类
public class Makeup implements Runnable{ static private Lipstick lipstick=new Lipstick(); //口红 static private Mirror mirror=new Mirror(); //镜子 private int choice; //0代表先拿口红,1代表先拿镜子mm private String name; public Makeup(int choice,String name) { this.choice = choice; this.name=name; } @Override public void run() { makeup(); } public void makeup(){ if(choice==0){ synchronized (lipstick){ System.out.println(name+"涂口红"); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } synchronized (mirror){ System.out.println(name+"照镜子"); } } }else{ synchronized (mirror){ System.out.println(name+"照镜子"); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } synchronized (lipstick){ System.out.println(name+"涂口红"); } } } } }
public class TestMakeup { public static void main(String[] args) { new Thread(new Makeup(0,"张柏芝")).start(); new Thread(new Makeup(1,"王菲")).start(); } }
解决方案:
将嵌套的同步机制改为“顺序”的同步机制,即我不需要同时占有,这里只是一个例子
if(choice==0){ synchronized (lipstick){ System.out.println(name+"涂口红"); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } synchronized (mirror){ System.out.println(name+"照镜子"); } }