例如下面的代码示例,sale1()中,obj锁需要持有this锁才能完成任务整体,而sale2()中,this锁需要持有obj锁才能完成任务整体。当两个线程都开始执行任务后,就开始产生死锁问题。
class Ticket implements Runnable { private int num; boolean flag = true; private Object obj = new Object(); Ticket(int num){ this.num = num; } public void sale1() { synchronized(obj) { //obj锁 sale2(); //this锁 } } public synchronized void sale2() { //this锁 synchronized(obj){ //obj锁 if(num>0) { num--; try{Thread.sleep(1);} catch (InterruptedException i){} System.out.println(Thread.currentThread().getName()+"========="+remain()); } } } //获取剩余票数 public int remain() { return num; } public void run(){ if(flag){ while(true) { sale1(); } } else { while(true) { sale2(); } } } } public class DeadLockDemo { public static void main(String[] args) { Ticket t = new Ticket(200); //创建多个线程对象 Thread t1 = new Thread(t); Thread t2 = new Thread(t); //开启多个线程使其执行任务 t1.start(); try{Thread.sleep(1);} catch (InterruptedException i){} t.flag = false; t2.start(); } }为了避免死锁,尽量不要在同步中嵌套同步,因为这样很容易造成死锁。