在以下类(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
可以两者兼而有之。