一、volitale和synchronized一起使用好麻烦
是否有疑问,需要保证多线程count++一个数时,需要添加volitale和synchronized两个一起才能实现,来回加锁,是不是有些麻烦?是否jdk有一个类,内部自动有锁,可以保证线程安全呢?答案是:肯定有。
二、Atomic类使用
AtomicXXX类实现线程安全,如下代码:
public class AtomicIntergerTest {
private AtomicInteger atomicInteger = new AtomicInteger(0);
public void add() {
for (int i = 0; i < 10000; i++) {
atomicInteger.incrementAndGet();
}
}
public static void main(String[] args) {
AtomicIntergerTest atomicIntergerTest = new AtomicIntergerTest();
List<Thread> list = new ArrayList<>();
for (int i = 0; i < 100; i++) {
list.add(new Thread(()->{
atomicIntergerTest.add();
}, "thread" + i));
}
list.forEach((o)->{
o.start();
});
list.forEach((o)->{
try {
o.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
});
System.out.println(atomicIntergerTest.atomicInteger);
}
}
运行结果:
三、Atomic类怎么实现线程安全的?
通过查阅代码和资料得知,Atomic类用的是CAS的技术,CAS:Compare and Swap,即比较再交换。
AtomicInteger.incrementAndGet的实现用了乐观锁技术,调用了类sun.misc.Unsafe库里面的 CAS算法,用CPU指令来实现无锁自增。
有人说:
AtomicInteger.incrementAndGet的自增比用synchronized的锁效率倍增
这个观点是不准确的,现在synchronized通过锁升级的方式,具体效率得实际场景测试得出,具体谁效率高不绝对。
四、CAS怎么实现线程安全的无锁自增的?
查看 atomicInteger.incrementAndGet();这个方法的源码
/**
* Atomically increments the current value,
* with memory effects as specified by {@link VarHandle#getAndAdd}.
*
* <p>Equivalent to {@code addAndGet(1)}.
*
* @return the updated value
*/
public final int incrementAndGet() {
return U.getAndAddInt(this, VALUE, 1) + 1;
}
/**
* Atomically adds the given value to the current value of a field
* or array element within the given object {@code o}
* at the given {@code offset}.
*
* @param o object/array to update the field/element in
* @param offset field/element offset
* @param delta the value to add
* @return the previous value
* @since 1.8
*/
@HotSpotIntrinsicCandidate
public final int getAndAddInt(Object o, long offset, int delta) {
int v;
do {
v = getIntVolatile(o, offset);
} while (!weakCompareAndSetInt(o, offset, v, v + delta));
return v;
}
CAS有3个操作数,内存值V,旧的预期值A,要修改的新值B。当且仅当预期值A和内存值V相同时,将内存值V修改为B,否则什么都不做。一直循环,循环到当且仅当预期值A和内存值V相同时,返回 v + delta 后的值。