【juc】cyclicbarrier人数凑齐发车

目录

        • 一、截图示例
        • 二、代码示例

一、截图示例

【juc】cyclicbarrier人数凑齐发车_第1张图片
【juc】cyclicbarrier人数凑齐发车_第2张图片

二、代码示例
package com.learning.cyclicbarrier;

import lombok.extern.slf4j.Slf4j;

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

/**
 * @Author wangyouhui
 * @Description 循环栅栏
 **/
@Slf4j
public class Learning_01
{ public static void main(String[] args) { ExecutorService service = Executors.newFixedThreadPool(3); CyclicBarrier barrier = new CyclicBarrier(3, ()->{ log.info("3个人已凑齐,发车"); }); for (int i = 0; i < 10; i++) { int j = i+1; service.submit(()->{ try { Thread.sleep(1000); log.info("第" + j + "车 1号座已入座"); barrier.await(); } catch (Exception e) { e.printStackTrace(); } }); service.submit(()->{ try { Thread.sleep(2000); log.info("第" + j + "车 2号座已入座"); barrier.await(); } catch (Exception e) { e.printStackTrace(); } }); service.submit(()->{ try { Thread.sleep(3000); log.info("第" + j + "车 3号座已入座"); barrier.await(); } catch (Exception e) { e.printStackTrace(); } }); } service.shutdown(); } }

你可能感兴趣的:(juc,juc)