标签:状态 tst try 跳过 释放 编程 ack pre import
字面意思回环栅栏,通过它可以实现让一组线程等待至某个状态之后再全部同时执行。
java.util.concurrent.CyclicBarrier 类是一种同步机制,它能够对处理一些算法的线程实现同步。换句话讲,它就是一个所有线程必须等待的一个栅栏,直到所有线程都到达这里,然后所有线程才可以继续做其他事情。
import java.util.concurrent.CyclicBarrier; public class Main { public static void main(String[] args) { int player_count = 10;//10个参赛选手 Admin admin = new Admin();//发令枪管理员 CyclicBarrier cyclicBarrier = new CyclicBarrier(player_count,admin); for(int i = 0;i < 10;i++){ Player player = new Player(cyclicBarrier); new Thread(player).start(); } } }
/** * 管理员发令开跑 */ public class Admin implements Runnable{ @Override public void run() { System.out.println("选手已来齐,跑"); } }
import java.util.concurrent.BrokenBarrierException; import java.util.concurrent.CyclicBarrier; /** * 选手 */ public class Player implements Runnable{ private CyclicBarrier cyclicBarrier; public Player(CyclicBarrier cyclicBarrier){ this.cyclicBarrier = cyclicBarrier; } @Override public void run() { System.out.println(Thread.currentThread().getName()+",准备跑"); try { cyclicBarrier.await(); } catch (InterruptedException e) { e.printStackTrace(); } catch (BrokenBarrierException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName()+"开跑"); } }
结果:
Thread-0,准备跑 Thread-1,准备跑 Thread-2,准备跑 Thread-4,准备跑 Thread-3,准备跑 Thread-5,准备跑 Thread-6,准备跑 Thread-7,准备跑 Thread-8,准备跑 Thread-9,准备跑 选手已来齐,跑 Thread-1开跑 Thread-0开跑 Thread-4开跑 Thread-7开跑 Thread-2开跑 Thread-9开跑 Thread-8开跑 Thread-6开跑 Thread-5开跑 Thread-3开跑
源码地址:https://github.com/qjm201000/concurrent_cyclicBarrier.git
并发编程-concurrent指南-回环栅栏CyclicBarrier
标签:状态 tst try 跳过 释放 编程 ack pre import
原文地址:https://www.cnblogs.com/qjm201000/p/10149974.html