12. java中的Atomic类
最后更新于
这有帮助吗?
最后更新于
这有帮助吗?
这有帮助吗?
public class LockCounter {
private volatile int counter;
public synchronized void increment() {
counter++;
}
}public class AtomicCounter {
private final AtomicInteger counter = new AtomicInteger(0);
public int getValue() {
return counter.get();
}
public void increment() {
while(true) {
int existingValue = getValue();
int newValue = existingValue + 1;
if(counter.compareAndSet(existingValue, newValue)) {
return;
}
}
}
}