使用CyclicBarrier模拟线程并发执行代码
2021-02-15 13:21
标签:int vol import row out final oid thread color 使用CyclicBarrier模拟线程并发执行代码 执行结果如下: Thread[pool-1-thread-10,5,main] = 1587018010565 使用CyclicBarrier模拟线程并发执行代码 标签:int vol import row out final oid thread color 原文地址:https://www.cnblogs.com/gaopengpy/p/12712600.htmlpackage 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 ) {
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-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
上一篇:Java知识点总结
下一篇:数据结构与算法-复杂度
文章标题:使用CyclicBarrier模拟线程并发执行代码
文章链接:http://soscw.com/index.php/essay/55672.html