“死锁”的形成 多个线程各自占有一些公共资源,并且互相等待其它线程占有的资源才能运行,而导致两个或者多个线程都在等待对方释放资源,都停止执行的情形。某一个同步块同时拥有“两个以上对象的锁”时,就可能会发生“死锁”的问题。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 package com.sympa.lesson01;public class DeadLock { public static void main (String[] args) { Play boy = new Play(); new Thread(boy, "Bob" ).start(); new Thread(boy, "Alice" ).start(); } } class Toy { } class Play implements Runnable { Toy toy1 = new Toy(); Toy toy2 = new Toy(); @Override public void run () { gg(); } public void gg () { if (Thread.currentThread().getName().equals("Bob" )){ synchronized (toy1){ System.out.println("Bob的toy1" ); try { Thread.sleep(1000 ); } catch (InterruptedException e){ e.printStackTrace(); } synchronized (toy2){ System.out.println("Bob的toy2" ); } } } else { synchronized (toy2){ System.out.println("Alice的toy2" ); try { Thread.sleep(2000 ); } catch (InterruptedException e){ e.printStackTrace(); } synchronized (toy1){ System.out.println("Alice的toy1" ); } } } } }