在通过 SCJP6 考试模拟器时,我发现了这样的问题:
class Clerk implements Runnable {
private Record A, B;
public Clerk(Record a, Record b) {
A = a;
B = b;
}
public void run() {
while(true) {
doStuff(A, B);
}
}
public synchronized void doStuff(Record a, Record b) {
synchronized(a) {
synchronized(b) {
a.add(1);
b.add(-1);
}}
}
}
然后
Record a = new Record();
Record b = new Record();
new Thread(new Clerk(a, b)).start();
new Thread(new Clerk(a, b)).start();
答案说这段代码会导致死锁,但我不明白——这到底是怎么可能的?有人可以帮我弄清楚吗?