使用CountDownLatch模拟高并发场景
生活随笔
收集整理的這篇文章主要介紹了
使用CountDownLatch模拟高并发场景
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;public class IncrTest {public static void concurrenceTest() {/*** 模擬高并發(fā)情況代碼*/final AtomicInteger atomicInteger = new AtomicInteger(0);final CountDownLatch countDownLatch = new CountDownLatch(1000); // 相當于計數(shù)器,當所有都準備好了,再一起執(zhí)行,模仿多并發(fā),保證并發(fā)量final CountDownLatch countDownLatch2 = new CountDownLatch(1000); // 保證所有線程執(zhí)行完了再打印atomicInteger的值ExecutorService executorService = Executors.newFixedThreadPool(10);try {for (int i = 0; i < 1000; i++) {executorService.submit(new Runnable() {@Overridepublic void run() {try {countDownLatch.await(); //一直阻塞當前線程,直到計時器的值為0,保證同時并發(fā)} catch (InterruptedException e) {e.printStackTrace();}//每個線程增加1000次,每次加1for (int j = 0; j < 1000; j++) {atomicInteger.incrementAndGet();}countDownLatch2.countDown();}});countDownLatch.countDown();}countDownLatch2.await();// 保證所有線程執(zhí)行完
System.out.println(atomicInteger);executorService.shutdown();}catch (Exception e){e.printStackTrace();}}public static void main(String[] args) throws InterruptedException {concurrenceTest();}
}
總結(jié)
以上是生活随笔為你收集整理的使用CountDownLatch模拟高并发场景的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Android 高仿QQ5.2双向側滑菜
- 下一篇: Node.js 开发技能图谱