java CyclicBarrier
来源:互联网 发布:cip数据查询 编辑:程序博客网 时间:2024/09/12 17:56
使用情况:你希望创建一组任务,他们并行执行,然后再进行下一个步骤之前等待,直到所有任务都完成
下面是一个赛马的例子,挺有意思的(java编程思想)
import java.util.concurrent.*;import java.util.*;public class Horse implements Runnable {private static int counter=0;private final int id=counter++;private int strides=0;private static Random rand=new Random(47);private static CyclicBarrier barrier;public Horse(CyclicBarrier barrier){this.barrier=barrier;}public synchronized int getStrides(){return strides;}@Overridepublic void run() {// TODO Auto-generated method stubtry{while(!Thread.interrupted()){synchronized(this){strides+=rand.nextInt(3);}barrier.await();}}catch(InterruptedException e){}catch(BrokenBarrierException e){throw new RuntimeException(e);}}public String toString(){return "Horse "+id+" ";}public String tracks(){StringBuilder s=new StringBuilder();for(int i=0;i<getStrides();i++){s.append("*");}s.append(id);return s.toString();}}
import java.util.concurrent.*;import java.util.*;public class HorseRace {public static final int FINISH_LINE=75;private List<Horse> horses =new ArrayList<Horse>();private ExecutorService exec=Executors.newCachedThreadPool();private CyclicBarrier barrier;public HorseRace(int nHorses,final int pause){barrier=new CyclicBarrier(nHorses,new Runnable(){public void run(){StringBuilder s=new StringBuilder();for(int i=0;i<FINISH_LINE;i++)s.append("=");System.out.println(s);for(Horse horse:horses)System.out.println(horse.tracks());for(Horse horse:horses){if(horse.getStrides()>=FINISH_LINE){System.out.println(horse+" won!");exec.shutdownNow();return;}try{TimeUnit.MILLISECONDS.sleep(pause);}catch(InterruptedException e){System.out.println("barrier-action sleep interrupted");}}}});for(int i=0;i<nHorses;i++){Horse horse=new Horse(barrier);horses.add(horse);exec.execute(horse);}}/** * @param args */public static void main(String[] args) {// TODO Auto-generated method stubint nHorses=7;int pause=200;new HorseRace(nHorses,pause);}}
0 0
- java CyclicBarrier
- Java CyclicBarrier
- Java CyclicBarrier
- java CyclicBarrier
- java CyclicBarrier
- Java CyclicBarrier
- java.util.concurrent.CyclicBarrier
- JAVA多线程CyclicBarrier应用
- Java多线程之CyclicBarrier
- Java多线程之CyclicBarrier
- Java CountDownLatch 和 CyclicBarrier
- java-concurrent之CyclicBarrier
- java CyclicBarrier(关卡)详解
- Java线程之CyclicBarrier
- java循环障碍CyclicBarrier
- Java之CyclicBarrier使用
- java.util.concurrent.CyclicBarrier
- java concurrent—CyclicBarrier
- UNIX网络编程之常用函数
- 第十二章:表视图常用UI范例——下拉刷新+无限滚动
- 爱奇艺上市的好故事与坏故事
- 苹果消息推送服务教程:第一部分(共2部分)
- HDU4788
- java CyclicBarrier
- 软件升级程序深入浅出
- 初始Mapr(六)——Mapr库和封装库
- unity3d学习笔记(五)--结合Mecanim实现怪物AI
- Java动态代理
- break -- continue
- linux中的IPC
- spring security之应用
- visual studio 中stdafx.h的作用