AtomicInteger

public final int getAndIncrement() {
for (;;) {
int current = get();
int next = current + 1;
if (compareAndSet(current, next))
return current;
}
}

这个方法可以保证线程安全:

自增的时候线程不安全:A线程,和B线程 自增 的到的结果一样

上述方法,通过自增完成以后比较之前的值,如果相同,将新的值赋值给 原来的值。

假如 A线程停止在 get(),然后B线程来了,执行完之后,改变了current的值,当A线程执行的时候,不会有任何操作。

--通过废弃一个线程来保证线程安全性

原文地址:https://www.cnblogs.com/mfser/p/7461758.html