Are they the same if we just considered the get/set methods? Or to say, are the following two pieces of code equivalent?
如果我们只考虑get / set方法,它们是否相同?或者说,以下两段代码是等价的吗?
private volatile boolean a;
public boolean isA(){
return a;
}
public void setA(boolean a){
this.a = a;
}
private AtomicBoolean a;
public boolean isA(){
return a.get();
}
public void setA(boolean a){
this.a.set(a);
}
1 个解决方案
#1
7
The advantage of the Atomic* classes are their atomic methods like 'getAndSet()' or 'compareAndSet()' which would otherwise require locking.
Atomic *类的优点是它们的原子方法,如'getAndSet()'或'compareAndSet()',否则需要锁定。
If you don't have any compound actions, e.g. just want to ensure that all threads see the latest value of 'a', then volatile is sufficient.
如果您没有任何复合动作,例如只是想确保所有线程都看到'a'的最新值,那么volatile就足够了。
#1
7
The advantage of the Atomic* classes are their atomic methods like 'getAndSet()' or 'compareAndSet()' which would otherwise require locking.
Atomic *类的优点是它们的原子方法,如'getAndSet()'或'compareAndSet()',否则需要锁定。
If you don't have any compound actions, e.g. just want to ensure that all threads see the latest value of 'a', then volatile is sufficient.
如果您没有任何复合动作,例如只是想确保所有线程都看到'a'的最新值,那么volatile就足够了。