欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

最简单的死锁

程序员文章站 2022-06-15 14:06:31
...

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() {
@Override
public 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();
}
}
}
相关标签: thread