package ecan.bi.test; import org.junit.Test; import java.io.IOException; import java.util.Random; import java.util.concurrent.CountDownLatch; import java.util.concurrent.CyclicBarrier; public class CyclicBarrierTest { class SoilderThreadGroup extends ThreadGroup { public SoilderThreadGroup() { super("soilder"); } } class Worker implements Runnable { private int index; private final CyclicBarrier cyclicBarrier; public Worker(int index, CyclicBarrier cyclicBarrier) { this.index = index; this.cyclicBarrier = cyclicBarrier; } @Override public void run() { try { System.out.println(Thread.currentThread().getThreadGroup().getName() + index + "报到"); cyclicBarrier.await(); doWork(); System.out.println(Thread.currentThread().getThreadGroup().getName() + index + "执行任务完成"); cyclicBarrier.await(); } catch (Exception e) { } } private void doWork() throws InterruptedException { Thread.sleep(new Random().nextInt(100) *10 ); } } class CallBackWork implements Runnable { private boolean flag; private final CountDownLatch countDownLatch; public CallBackWork(boolean flag,CountDownLatch countDownLatch) { this.flag = flag; this.countDownLatch = countDownLatch; } @Override public void run() { if (flag) { System.out.println("任务全部完成"); countDownLatch.countDown(); } else { System.out.println("士兵全部集结"); flag = true; } } } @Test public void test() throws IOException, InterruptedException { CountDownLatch countDownLatch = new CountDownLatch(1); CyclicBarrier cyclicBarrier = new CyclicBarrier(10, new Thread(new CallBackWork(false,countDownLatch))); SoilderThreadGroup soilderThreadGroup = new SoilderThreadGroup(); for (int i = 0; i < 10; i++) { Thread thread = new Thread(soilderThreadGroup, new Worker(i, cyclicBarrier)); thread.start(); } countDownLatch.await(); } }
CountDownLatch 和CyclicBarrier的使用
最新推荐文章于 2022-07-08 12:22:35 发布