模拟并发环境代码段

使用CountDownLatch来控制线程们一起启动模拟并发

总体思路:

使用两个计数器,一个计数器start只有一个数,每个线程启动后都卡这个计数器这里start.await();

再用第二个计数器end,当一个线程执行完,这个计数器-1

然后start-1,所有线程瞬间不会阻塞了,也就是模拟了一个并发的环境

最后end.await();主线程阻塞到执行完毕,后面可以加个计时或者啥的算一下时间等等

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

        int threadNumber = 100;
        CountDownLatch start = new CountDownLatch(1);
        CountDownLatch end = new CountDownLatch(threadNumber);
        ExecutorService executorService = Executors.newFixedThreadPool(threadNumber);
        for (int i = 0; i < threadNumber; i++) {
            executorService.submit(() -> {
                try {
                    // 先阻塞这别让这个线程跑起来
                    start.await();
                    // 具体的业务方法(本地方法 or 远程调用)
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    // 一个线程跑完 end计数器-1
                    end.countDown();
                }
            });
        }

        // start-1 所有线程启动,模拟并发
        start.countDown();
        // 阻塞直到执行完毕
        end.await();
        executorService.shutdown();

    }
}

模拟并发环境代码段
https://www.powercheng.fun/articles/3b4b1d9a/
作者
powercheng
发布于
2022年2月28日
许可协议