1. 程式人生 > >高併發-原子性-AtomicInteger

高併發-原子性-AtomicInteger

執行緒不安全:

//請求總次數
private static int totalCount = 10000;
//最大併發數
private static int totalCurrency = 100;
//計數初始值
private static int count = 0;

public static void main(String[] args) throws InterruptedException {
final CountDownLatch countDownLatch = new CountDownLatch(totalCount);
final Semaphore semaphore = new Semaphore(totalCurrency);
ExecutorService executorService = Executors.newCachedThreadPool();
for (int i = 0; i < totalCount; i++) {
executorService.execute(new Runnable() {
@Override
public void run() {
try {
semaphore.acquire();
//本身執行緒不安全
count++;

semaphore.release();
countDownLatch.countDown();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
}
//其他執行緒執行完成執行下面操作
countDownLatch.await();
executorService.shutdown();
System.out.println(count);
}

執行緒安全:

 //總共請求次數10000次 數值給大點 不然效果不明顯
private static int totalCount = 10000;
//最大併發數 100個 數值給大點 不然效果不明顯
private static int totalCurrency = 100;
// private static int count = 0;
//使用原子類修飾
private static AtomicInteger atomicInteger = new AtomicInteger(0);

public static void main(String[] args) throws InterruptedException {

final CountDownLatch countDownLatch = new CountDownLatch(totalCount);
final Semaphore semaphore = new Semaphore(totalCurrency);
ExecutorService executorService = Executors.newCachedThreadPool();
for (int i = 0; i < totalCount; i++) {
executorService.execute(() -> {
try {
semaphore.acquire();
atomicInteger.incrementAndGet();

semaphore.release();
countDownLatch.countDown();
} catch (InterruptedException e) {
e.printStackTrace();
}
});
}
//其他執行緒完成各自任務 countDownLatch.count==0
countDownLatch.await();
executorService.shutdown();
System.out.println(atomicInteger);

}