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

Posted gaopengpy

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用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

以上是关于使用CyclicBarrier模拟线程并发执行代码的主要内容,如果未能解决你的问题,请参考以下文章

并发编程系列之CyclicBarrier用法简介

并发编程系列之CyclicBarrier用法简介

Java并发多线程编程——CyclicBarrier

25.大白话说java并发工具类-CountDownLatch,CyclicBarrier,Semaphore,Exchanger

java并发之同步辅助类CyclicBarrier

Java并发编程之-了解CyclicBarrier