用栅栏(CyclicBarrier)实现高并发测试

public class TestCyclic {
    @Test
    public void test01() {
        int count = 10000;//并发线程数
        CyclicBarrier cyclicBarrier = new CyclicBarrier(count);
        ExecutorService executorService = Executors.newFixedThreadPool(count);
        int n = 0;
        for (int i = 0; i < count; i++) {

            executorService.execute(new TestCyclic().new Task(cyclicBarrier, n));
            n++;
        }
        executorService.shutdown(); // 关闭线程池
        // 判断是否所有的线程已经运行完
        while (!executorService.isTerminated()) {
            try {
                // 所有线程池中的线程执行完毕,执行后续操作
                // TODO
                System.out.println("==============is sleep============");
                Thread.sleep(10000);
                System.out.println("==============is wake============");

            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public class Task implements Runnable {
        private CyclicBarrier cyclicBarrier;
        int n = 0;

        public Task(CyclicBarrier cyclicBarrier, int n) {
            this.cyclicBarrier = cyclicBarrier;
            this.n = n;
        }

        @Override
        public void run() {
            try {
                // 等待所有任务准备就绪
                System.out.println("赛马" + n + "到达栅栏前");
                cyclicBarrier.await();
                System.out.println("赛马" + n + "开始跑");
                // 测试内容
                System.out.println("hello: " + n);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

你可能感兴趣的:(学习-Java)