多个线程共同的等待一个操作

转自:http://blackproof.iteye.com/blog/1525238

多个线程共同的等待一个操作(N-1),可以多次使用这个barrier对象,他不同于cutdownlatch锁,他可以多次重复使用

 

以下为实例:

 

Java代码    收藏代码
  1. package com.common;  
  2.   
  3. import java.util.Random;    
  4. import java.util.concurrent.CyclicBarrier;    
  5. import java.util.concurrent.ExecutorService;    
  6. import java.util.concurrent.Executors;    
  7. import java.util.regex.Pattern;  
  8.     
  9.     
  10. public class CyclicBarrierTest {    
  11.     
  12.     public static void main(String[] args) {   
  13.         String value = "-43.23";  
  14.         String reg = "^(-?\\d+)(\\.\\d+)?$";  
  15.         Pattern pattern = Pattern.compile(reg); //正则  
  16.         pattern.matcher(value).toString();  
  17.           
  18.         final CyclicBarrier barrier = new CyclicBarrier(10new Runnable(){    
  19.             public void run() {    
  20.                 System.out.println("大部队集合完毕了。");    
  21.                 try {  
  22.                     Thread.sleep(3000);  
  23.                 } catch (InterruptedException e) {  
  24.                     // TODO Auto-generated catch block  
  25.                     e.printStackTrace();  
  26.                 }  
  27.             }    
  28.                 
  29.         });    
  30.             
  31.         ExecutorService executor = Executors.newFixedThreadPool(10);    
  32.         for(int i = 0; i<10; i++){    
  33.             final int num = i;    
  34.             executor.execute(new Runnable(){    
  35.                 public void run() {    
  36.                     System.out.println("num: " + num + " 从公司出发了.");    
  37.                     try {    
  38.                         Thread.sleep(new Random().nextInt(1000));    
  39.                         barrier.await(); // 在西湖等待大部队    
  40.                         
  41.                         System.out.println("num: " + num + " 在西湖开始游玩.");    
  42.                             
  43.                         Thread.sleep(new Random().nextInt(2000));    
  44.                         barrier.await(); //等待大部队就餐    
  45.                     } catch (Exception e1) {    
  46.                     }                       
  47.                 }                   
  48.             });    
  49.         }    
  50.     
  51.         executor.shutdown();    
  52.     }    
  53. }    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值