J.U.C工具包之CyclicBarrier
什么是CyclicBarrier:
例子:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
import java.util.concurrent.BrokenBarrierException; import java.util.concurrent.CyclicBarrier; public class CyclicBarrierDemo { public static void main(String[] args) throws InterruptedException { new CyclicBarrierDemo().test(); } private void test() throws InterruptedException { CyclicBarrier cyclicBarrier = new CyclicBarrier(3); new Thread(new Task(cyclicBarrier), "Thread1").start(); Thread.sleep(1000); new Thread(new Task(cyclicBarrier), "Thread2").start(); Thread.sleep(1000); new Thread(new Task(cyclicBarrier), "Thread3").start(); } class Task implements Runnable { private CyclicBarrier cyclicBarrier; public Task(CyclicBarrier cyclicBarrier) { this.cyclicBarrier = cyclicBarrier; } @Override public void run() { System.out .println("Thread:" + Thread.currentThread().getName() + " starttime:" + System.currentTimeMillis()); try { cyclicBarrier.await(); } catch (InterruptedException | BrokenBarrierException e) { e.printStackTrace(); } System.out .println("Thread:" + Thread.currentThread().getName() + " start process:" + System.currentTimeMillis()); } } } |
执行结果:
1 2 3 4 5 6 7 |
Thread:Thread1 starttime:1596530849984 Thread:Thread2 starttime:1596530850984 Thread:Thread3 starttime:1596530851985 /**这里所有线程未执行完成,均在等待计数为0后才完成后续执行*/ Thread:Thread3 start process:1596530851985 Thread:Thread1 start process:1596530851985 Thread:Thread2 start process:1596530851985 |
暂无评论