并发编程系列---【CyclicBarrier】
作者:互联网
作用:执行第一个参数指定的次数之后,最后一个线程执行第二个参数中的任务。
应用场景:在微服务中调用五个接口,确保5个接口执行完毕,再执行自己的业务逻辑。
import java.util.Random; import java.util.concurrent.CyclicBarrier; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class CyclicBarrierDemo { static class Task implements Runnable { CyclicBarrier barrier; public Task(CyclicBarrier barrier) { this.barrier = barrier; } @Override public void run() { try { Thread.sleep(new Random().nextInt(10) * 1000); System.out.println(Thread.currentThread().getName() + " 检查火箭"); barrier.await();//标记子任务执行完了,让count++ => 满足count => 调用CyclicBarrier的参数2任务 } catch (Exception e) { e.printStackTrace(); } } } public static void main(String[] args) { int count = 10; ExecutorService exec = Executors.newFixedThreadPool(count); CyclicBarrier barrier = new CyclicBarrier(5, new Runnable() { @Override public void run() { System.out.println(Thread.currentThread().getName() + " -------------------发射火箭"); } }); for(int i = 0; i < count; i++) { exec.execute(new Task(barrier)); } exec.shutdown(); } }
标签:count,util,barrier,编程,---,import,CyclicBarrier,public 来源: https://www.cnblogs.com/hujunwei/p/15659616.html