使用CyclicBarrier模拟线程并发执行代码

使用CyclicBarrier模拟线程并发执行代码

package com.gaopeng.multithread;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 使用CyclicBarrier模拟线程并发执行代码
 * 
 * @author gaopeng
 *
 */
public class ConcurrentTest {

    // 并发数
    private static final int threadNum = 10;

    private static volatile CountDownLatch countDownLatch = new CountDownLatch(threadNum);

    private static volatile CyclicBarrier cyclicBarrier = new CyclicBarrier(threadNum);

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

        ExecutorService executorService = Executors.newFixedThreadPool(threadNum);

        for (int i = 0; i < threadNum; i++) {
            executorService.execute(() -> {
                try {
                    // 所有的线程在这里等待
                    cyclicBarrier.await();

                    System.out.println(Thread.currentThread() + " = " + System.currentTimeMillis());

                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    countDownLatch.countDown();
                }

            });
        }

        // 等待所有线程执行完毕再关闭线程池
        countDownLatch.await();

        executorService.shutdown();

    }

}

执行结果如下:

Thread[pool-1-thread-10,5,main] = 1587018010565
Thread[pool-1-thread-9,5,main] = 1587018010565
Thread[pool-1-thread-8,5,main] = 1587018010565
Thread[pool-1-thread-7,5,main] = 1587018010565
Thread[pool-1-thread-6,5,main] = 1587018010565
Thread[pool-1-thread-2,5,main] = 1587018010565
Thread[pool-1-thread-5,5,main] = 1587018010565
Thread[pool-1-thread-4,5,main] = 1587018010565
Thread[pool-1-thread-3,5,main] = 1587018010565
Thread[pool-1-thread-1,5,main] = 1587018010565

posted @ 2020-04-16 14:21  gaopengpy  阅读(278)  评论(0编辑  收藏  举报