Java 同步器
?
?
?
?
?
?
?
?
?
?
CyclicBarrier是什么
CyclicBarrier也叫同步屏障,在JDK1.5被引入,可以讓一組線程達到一個屏障時被阻塞,直到最后一個線程達到屏障時,所以被阻塞的線程才能繼續執行。
CyclicBarrier好比一扇門,默認情況下關閉狀態,堵住了線程執行的道路,直到所有線程都就位,門才打開,讓所有線程一起通過。
構造方法
CyclicBarrier.png
應用場景
想象一個場景,運動會男子100米決賽,8名選手。
Athlete.java :每個運動員都就位后才開始。
class Athlete implements Runnable {private CyclicBarrier cyclicBarrier;private String name;public Athlete(CyclicBarrier cyclicBarrier, String name) {this.cyclicBarrier = cyclicBarrier;this.name = name;}@Overridepublic void run() {System.out.println(name + "就位");try {cyclicBarrier.await();Random random =new Random();double time = random.nextDouble() + 9;System.out.println(name + ": "+ time);} catch (Exception e) {}} }Race.java : 負責屏障的初始化。
class Race {private CyclicBarrier cyclicBarrier = new CyclicBarrier(8);public void start() {List<Athlete> athleteList = new ArrayList<>();athleteList.add(new Athlete(cyclicBarrier,"博爾特"));athleteList.add(new Athlete(cyclicBarrier,"鮑威爾"));athleteList.add(new Athlete(cyclicBarrier,"蓋伊"));athleteList.add(new Athlete(cyclicBarrier,"布雷克"));athleteList.add(new Athlete(cyclicBarrier,"加特林"));athleteList.add(new Athlete(cyclicBarrier,"蘇炳添"));athleteList.add(new Athlete(cyclicBarrier,"路人甲"));athleteList.add(new Athlete(cyclicBarrier,"路人乙"));Executor executor = Executors.newFixedThreadPool(8);for (Athlete athlete : athleteList) {executor.execute(athlete);}} }?
?
轉載于:https://www.cnblogs.com/diegodu/p/7339423.html
總結
- 上一篇: 【NOIP 2017】列队
- 下一篇: Photometric Stereo 光