码迷,mamicode.com
首页 > 其他好文 > 详细

CyclicBarrier 使用说明

时间:2015-11-27 10:56:13      阅读:128      评论:0      收藏:0      [点我收藏+]

标签:

字面意思回环栅栏,通过它可以实现让一组线程等待至某个状态之后再全部同时执行。叫做回环是因为当所有等待线程都被释放以后,CyclicBarrier可以被重用。
 
主要方法:
     public int await() throws InterruptedException, BrokenBarrierException
     用来挂起当前线程,直至所有线程都到达barrier状态再同时执行后续任务。
 
例子:
     跟团旅游,没到一个景点导游给介绍完后,让大家自由活动,然后约定好(某个时间)在下一个景点集合。
  
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 service = Executors. newCachedThreadPool();
               final CyclicBarrier cb = new CyclicBarrier(3);
               for(int i = 0; i < 3; i++){
                     Runnable runnable = new Runnable(){
                            public void run(){
                                   try {
                                         Thread. sleep((long)(Math. random()*10000));     
                                         System. out.println("线程" + Thread.currentThread().getName() +
                                                        "即将到达集合地点1,当前已有" + (cb.getNumberWaiting()+1) + "个已经到达," + (cb.getNumberWaiting()==2?"都到齐了,继续走啊":"正在等候" ));                                        
                                         cb.await();
                                         
                                         Thread. sleep((long)(Math. random()*10000));     
                                         System. out.println("线程" + Thread.currentThread().getName() +
                                                        "即将到达集合地点2,当前已有" + (cb.getNumberWaiting()+1) + "个已经到达," + (cb.getNumberWaiting()==2?"都到齐了,继续走啊":"正在等候" ));
                                         cb.await();   
                                         Thread. sleep((long)(Math. random()*10000));     
                                         System. out.println("线程" + Thread.currentThread().getName() +
                                                        "即将到达集合地点3,当前已有" + (cb.getNumberWaiting() + 1) + "个已经到达," + (cb.getNumberWaiting()==2?"都到齐了,继续走啊":"正在等候" ));                                      
                                         cb.await();                                     
                                  } catch (Exception e) {
                                         e.printStackTrace();
                                  }                          
                           }
                     };
                     service.execute(runnable);
              }
              service.shutdown();
       }
}

CyclicBarrier 使用说明

标签:

原文地址:http://www.cnblogs.com/tstd/p/4999806.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!