Java1.5 Atomic并发原子类
类似AtomicInteger这样的类是Java1.5为了高并发提供的原子类。
可见性
AtomicInteger的值已经被volatile修饰,具有可见性,也就是value被修改后其他线程马上就可以知道。
private volatile int value;
这里有一个例外:
/**
* Eventually sets to the given value.
*
* @param newValue the new value
* @since 1.6
*/
public final void lazySet(int newValue) {
unsafe.putOrderedInt(this, valueOffset, newValue);
}
如果使用的是lazySet方法来修改value,别的线程不会马上看见。
原子性
主要思想是:用不断的重试代替阻塞。
在改变value前先检查这个value是否已经被其它线程修改过了。
AtomicInteger moneyInt = new AtomicInteger(0);
ThreadPoolExecutor executor = new ThreadPoolExecutor(1000, 1000, 1000, TimeUnit.MILLISECONDS, new LinkedBlockingDeque<Runnable>(1));
for (int i = 0; i < 1000; i++) {
executor.execute(() -> {
while (true) {
int oldValue = moneyInt.get();
int newValue = oldValue + 1;
boolean success = moneyInt.compareAndSet(oldValue, newValue); //比较并改变值,如果成功返回true
if (!success) {
System.out.println("修改不成功");
} else {
break;
}
}
});
}
executor.shutdown();
while (true) {
if (executor.isTerminated()) {
System.out.println(moneyInt.get());
break;
}
}
通过ActomicInteger可以完成具有原子性的自增和自减:
AtomicInteger i = new AtomicInteger();
i.getAndIncrement(); //等于i++
i.incrementAndGet(); //等于++i