4.4可见性
Last updated
Last updated
graph TB
A[普通读]-->B[普通写]
B[普通写]-->C[StoreStore屏障]
C[StoreStore屏障]-->D[Volatile写]
D[Volatile写]-->E[StoreLoad屏障]graph TB
volatile读-->LoadLoad屏障
LoadLoad屏障-->LoadStore屏障
LoadStore屏障-->普通读
普通读-->普通写package com.moluo.concurrency.count;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
public class VolatileCountExample {
public static int clientTotal = 5000;
public static int threadTotal = 200;
public static volatile int count = 0;
public static void main(String[] args) throws InterruptedException {
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 (InterruptedException e) {
e.printStackTrace();
}
countDownLatch.countDown();
});
}
countDownLatch.await();
executorService.shutdown();
System.out.println("count:" + count);
}
private static void add() {
count++;
}
}volatile boolean isInited=false;
// 线程1:
context =loadContext();
isInited=true;
// 线程2:
while(!isInited){
sleep();
}
doSomethingWithConfig(context)