1.原子性:提供互斥访问,同一时刻只能有一个线程对数据进行操作,(atomic,synchronized);
2.可见性:一个线程对主内存的修改可以及时地被其他线程看到,(synchronized,volatile);
3.有序性:一个线程观察其他线程中的指令执行顺序,由于指令重排序,该观察结果一般杂乱无序,(happens-before原则)。
接下来,依次分析。
二、原子性—atomic
==============
JDK里面提供了很多atomic类,AtomicInteger,AtomicLong,AtomicBoolean等等。
它们是通过CAS完成原子性。
我们一次来看AtomicInteger,AtomicStampedReference,AtomicLongArray,AtomicBoolean。
(1)AtomicInteger
================
先来看一个AtomicInteger例子:
public class AtomicIntegerExample1 {
// 请求总数
public static int clientTotal = 5000;
// 同时并发执行的线程数
public static int threadTotal = 200;
public static AtomicInteger count = new AtomicInteger(0);
public static void main(String[] args) throws Exception {
ExecutorService executorService = Executors.newCachedThreadPool();//获取线程池
final Semaphore semaphore = new Semaphore(threadTotal);//定义信号量
final CountDownLatch countDownLatch = new CountDownLatch(clientTotal);
for (int i = 0; i < clientTotal ; i++) {
executorService.execute(() -> {
try {
semaphore.acquire();
add();
semaphore.release();
} catch (Exception e) {
log.error(“exception”, e);
}
countDownLatch.countDown();
});
}
countDownLatch.await();
executorService.shutdown();
log.info(“count:{}”, count.get());
}
private static void add() {
count.incrementAndGet();
}
}
我们可以执行看到最后结果是5000是线程安全的。
那么看AtomicInteger的incrementAndGet()方法:
再看getAndAddInt()方法: