java并发测试帮助方法

孤街浪徒 提交于 2020-01-17 11:00:13
public class SimulateHighConcurrency {

    public static void run(int num, Consumer<Thread> action) {
        Objects.requireNonNull(action);
        CountDownLatch countDownLatch = new CountDownLatch(1);
        for (int i = 0; i < num; i++) {
            new Thread(() -> {
                try {
                    action.accept(Thread.currentThread());
                    countDownLatch.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }).start();
        }
        //线程创建完成之后同时启动
        countDownLatch.countDown();
    }

    public static void main(String[] args) throws InterruptedException {
        CountDownLatch doneSignal = new CountDownLatch(2000);
        SimulateHighConcurrency.run(2000, (t) -> {
            System.out.println(t.getName());
            doneSignal.countDown();
        });
        doneSignal.await();
        System.out.println("done");
    }

}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!