当两个线程互相等待对方的监视器时会发生死锁,所有线程处于阻塞状态,无法运行。在系统有多个监视器的情况下,死锁是很容易发生的。
class A { public synchronized void foo(B b) { System.out.println("Thread:" + Thread.currentThread().getName() + "run in foo() method of instance A"); try { Thread.sleep(200); } catch (InterruptedException ex) { ex.printStackTrace(); } System.out.println("Thread:" + Thread.currentThread().getName() + "call last() of B class"); b.last(); } public synchronized void last() { System.out.println("last() of A..."); } } class B { public synchronized void bar(A a) { System.out.println("Thread:" + Thread.currentThread().getName() + "run in bar() method of instance B"); try { Thread.sleep(200); } catch (InterruptedException ex) { ex.printStackTrace(); } System.out.println("Thread:" + Thread.currentThread().getName() + "call last() of A class"); a.last(); } public synchronized void last() { System.out.println("last() of B..."); } } public class DeadLock implements Runnable { A a = new A(); B b = new B(); public void init() { Thread.currentThread().setName("main Thread"); a.foo(b); System.out.println("run in main Thread..."); } @Override public void run() { Thread.currentThread().setName("dut Thread"); b.bar(a); System.out.println("run in main Thread..."); } public void main() { DeadLock d = new DeadLock(); new Thread(d).start(); d.init(); } }