我试图在我的程序中实现死锁,除了一个我无法解释的问题外,一切都很好。
public class Test {
public static void main(String[] args) throws InterruptedException {
Integer balanceA = 10000;
Integer balanceB = 10000;
Thread t1 = new Thread(() -> {
while (true) {
Processor.run(balanceA, balanceB);
}
});
Thread t2 = new Thread(() -> {
while (true) {
Processor.run(balanceB, balanceA);
}
});
t1.start();
t2.start();
t1.join();
t2.join();
}
}
class Processor {
public static void run(Integer balanceA, Integer balanceB) {
synchronized (balanceA) {
synchronized (balanceB) {
System.out.println(balanceA++ + "; " + balanceB--);
}
}
}
}
为什么它总是向我显示与我没有修改整数值相同的结果:
10000;10000
10000;10000
。
>balanceA++
等效于balanceA = balance + 1
。它不会修改Integer
(它不能,因为Integer
是不可变的)。它只是更改 balanceA
参数的值以引用不同的对象。
如果使用 AtomicInteger
并调用 incrementAndGet
或 getAndIncrement
,则会看到值发生更改。您也不需要任何同步。