读书人

最简略的死锁

发布时间: 2012-09-24 13:49:41 作者: rapoo

最简单的死锁

public class Client {public static void main(String[] args) throws Throwable {List a = new ArrayList();List b = new ArrayList();new Collector("collector1", a, b).collect();new Collector("collector2", b, a).collect();}static class Collector {private String name = "";private Object lockA = null;private Object lockB = null;public Collector(String name, Object a, Object b) {this.name = name;this.lockA = a;this.lockB = b;}public void collect() {new Thread(new Runnable() {@Overridepublic void run() {synchronized (lockA) {System.out.println(name + " got first...");try {Thread.currentThread().sleep(10);} catch (InterruptedException e) {}synchronized (lockB) {System.out.println(name + " got all.");}}}}, name).start();}}}

读书人网 >编程

热点推荐