zoukankan      html  css  js  c++  java
  • 学习多线程6---栅栏

    CyclicBarrier用于模拟所有线程都到达一个临界条件后在进行下一步,CyclicBarrier使用在run函数里面

    下面是一个使用例子

       

    package com.condition;
    
    import java.util.concurrent.BrokenBarrierException;
    import java.util.concurrent.CyclicBarrier;
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    
    public class CyclicBarrierTest {
    
    	public static void main(String[] args) {
    		ExecutorService threadPool = Executors.newCachedThreadPool();
    		final CyclicBarrier cb = new CyclicBarrier(3);
    		for(int i = 0; i < 3;i++){
    			Runnable runnable = new Runnable(){
    				@Override
    				public void run() {
    					try {
    						Thread.sleep((long) (Math.random()*10000));
    					} catch (InterruptedException e) {
    						// TODO Auto-generated catch block
    						e.printStackTrace();
    					}
    					System.out.println(1+Thread.currentThread().getName()
    						+" 当前已有 "+cb.getNumberWaiting());
    					try {
    						cb.await();
    					} catch (InterruptedException e) {
    						// TODO Auto-generated catch block
    						e.printStackTrace();
    					} catch (BrokenBarrierException e) {
    						// TODO Auto-generated catch block
    						e.printStackTrace();
    					}
    					try {
    						Thread.sleep((long) (Math.random()*10000));
    					} catch (InterruptedException e) {
    						// TODO Auto-generated catch block
    						e.printStackTrace();
    					}
    					System.out.println(2+Thread.currentThread().getName()
    						+" 当前已有 "+cb.getNumberWaiting());
    					try {
    						cb.await();
    					} catch (InterruptedException e) {
    						// TODO Auto-generated catch block
    						e.printStackTrace();
    					} catch (BrokenBarrierException e) {
    						// TODO Auto-generated catch block
    						e.printStackTrace();
    					}
    				}
    			};
    			 threadPool.execute(runnable);
    		}
    	}
    
    }
    

      

        

  • 相关阅读:
    个人作业3——个人总结(Alpha阶段)
    结对编程2 单元测试
    英语学习app案例分析
    结对作业1
    java四则运算生成器
    个人附加作业 201421123108 王坤彬 网络1414
    个人作业3-(Alpha阶段)
    结对编程之单元测试 201421123108 王坤彬
    英语学习案例分析APP 201421123108 王坤彬
    结对编程 王坤彬 201421123108
  • 原文地址:https://www.cnblogs.com/hzmbbbb/p/4280293.html
Copyright © 2011-2022 走看看