在以下类(class)中,

// This class should be thread-safe!!!
class BankAccount {

    private long balance; // Should it be volatile?

    synchronized void deposit(long amount) {
        // ...
        balance += amount;
    }

    synchronized void withdraw(long amount) {
        // ...
        balance -= amount;
    }
}

我应该在volatile字段中添加balance吗?

最佳答案

不,与synchronized关键字相比,volatile是轻量级的。
volatile可以保证阅读器线程始终获得新的balance值,但不能使balance += amount;成为原子。 synchronized可以两者兼而有之。

09-16 17:30