public class CountDownDemo { private static final int CORE_POOL_SIZE = 4; private static final int MAX_POOL_SIZE = 8; private static final long KEEP_ALIVE_TIME = 5L; private final static int QUEUE_SIZE = 1600; protected final static ExecutorService THREAD_POOL = new ThreadPoolExecutor(CORE_POOL_SIZE, MAX_POOL_SIZE, KEEP_ALIVE_TIME, TimeUnit.SECONDS, new LinkedBlockingQueue<>(QUEUE_SIZE)); public static void main(String[] args) throws InterruptedException { // 新建一个为5的计数器 CountDownLatch countDownLatch = new CountDownLatch(5); OrderInfo orderInfo = new OrderInfo(); THREAD_POOL.execute(() -> { System.out.println("当前任务Customer,线程名字为:" + Thread.currentThread().getName()); orderInfo.setCustomerInfo(new CustomerInfo()); countDownLatch.countDown(); }); THREAD_POOL.execute(() -> { System.out.println("当前任务Discount,线程名字为:" + Thread.currentThread().getName()); orderInfo.setDiscountInfo(new DiscountInfo()); countDownLatch.countDown(); }); THREAD_POOL.execute(() -> { System.out.println("当前任务Food,线程名字为:" + Thread.currentThread().getName()); orderInfo.setFoodListInfo(new FoodListInfo()); countDownLatch.countDown(); }); THREAD_POOL.execute(() -> { System.out.println("当前任务Tenant,线程名字为:" + Thread.currentThread().getName()); orderInfo.setTenantInfo(new TenantInfo()); countDownLatch.countDown(); }); THREAD_POOL.execute(() -> { System.out.println("当前任务OtherInfo,线程名字为:" + Thread.currentThread().getName()); orderInfo.setOtherInfo(new OtherInfo()); countDownLatch.countDown(); }); countDownLatch.await(1, TimeUnit.SECONDS); System.out.println("主线程:" + Thread.currentThread().getName()); } }
View Code建立一个线程池(具体配置根据具体业务,具体机器配置),进行并发的执行我们的任务(生成用户信息,菜品信息等),最后利用await方法阻塞等待结果成功返回。
循环栅栏CyclicBarrier字面意思循环栅栏,栅栏就是一种障碍物。这里就是内存屏障。通过它可以实现让一组线程等待至某个状态之后再全部同时执行。叫做回环是因为当所有等待线程都被释放以后,CyclicBarrier可以被重用。CyclicBarrier比CountDownLatch 功能更强大一些,CyclicBarrier可以接受一个参数作为barrierAction。所谓barrierAction就是当计算器一次计数完成后,系统会执行的动作。CyclicBarrier强调的是n个线程,大家相互等待,只要有一个没完成,所有人都得等着。(这种思想在高性能计算最为常见,GPU计算中关于也有类似内存屏障的用法)。构造函数如下,其中parties表示计数总数,也就是参与的线程总数。
public CyclicBarrier(int parties, Runnable barrierAction) { } public CyclicBarrier(int parties) { }
案例10个人去旅行,规定达到一个地点后才能继续前行.代码如下
class CyclicBarrierWorker implements Runnable { private int id; private CyclicBarrier barrier; public CyclicBarrierWorker(int id, final CyclicBarrier barrier) { this.id = id; this.barrier = barrier; } @Override public void run() { try { Thread.sleep(Math.abs(new Random().nextInt()%10000)); System.out.println(id + " th people wait"); barrier.await(); // 大家等待最后一个线程到达 } catch (InterruptedException | BrokenBarrierException e) { e.printStackTrace(); } } } public class TestCyclicBarrier { public static void main(String[] args) { int num = 10; CyclicBarrier barrier = new CyclicBarrier(num, new Runnable() { @Override public void run() { System.out.println("go on together!"); } }); for (int i = 1; i <= num; i++) { new Thread(new CyclicBarrierWorker(i, barrier)).start(); } } }
View Code