当前位置:首页 > 开发 > 编程语言 > Java > 正文

java CyclicBarrier 实例

发表于: 2012-05-13   作者:blackproof   来源:转载   浏览:
摘要: 多个线程等待   多个线程共同的等待一个操作(N-1),可以多次使用这个barrier对象,他不同于cutdownlatch锁,他可以多次重复使用   以下为实例:   package com.common; import java.util.Random; import java.util.concurrent.CyclicBarrier;

多个线程等待

 

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

 

以下为实例:

 

package com.common;

import java.util.Random;  
import java.util.concurrent.CyclicBarrier;  
import java.util.concurrent.ExecutorService;  
import java.util.concurrent.Executors;  
import java.util.regex.Pattern;
  
  
public class CyclicBarrierTest {  
  
    public static void main(String[] args) { 
    	String value = "-43.23";
    	String reg = "^(-?\\d+)(\\.\\d+)?$";
    	Pattern pattern = Pattern.compile(reg); //正则
    	pattern.matcher(value).toString();
    	
        final CyclicBarrier barrier = new CyclicBarrier(10, new Runnable(){  
            public void run() {  
                System.out.println("大部队集合完毕了。");  
                try {
					Thread.sleep(3000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
            }  
              
        });  
          
        ExecutorService executor = Executors.newFixedThreadPool(10);  
        for(int i = 0; i<10; i++){  
            final int num = i;  
            executor.execute(new Runnable(){  
                public void run() {  
                    System.out.println("num: " + num + " 从公司出发了.");  
                    try {  
                        Thread.sleep(new Random().nextInt(1000));  
                        barrier.await(); // 在西湖等待大部队  
                      
                        System.out.println("num: " + num + " 在西湖开始游玩.");  
                          
                        Thread.sleep(new Random().nextInt(2000));  
                        barrier.await(); //等待大部队就餐  
                    } catch (Exception e1) {  
                    }                     
                }                 
            });  
        }  
  
        executor.shutdown();  
    }  
}  

    主要的逻辑都在一个函数中

 
private int dowait(boolean timed, long nanos)
        throws InterruptedException, BrokenBarrierException,
               TimeoutException {
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            final Generation g = generation;

            if (g.broken)
                throw new BrokenBarrierException();

            if (Thread.interrupted()) {
                breakBarrier();
                throw new InterruptedException();
            }

           int index = --count;                        //lock锁计数器递减
           if (index == 0) {                            // tripped,当计数器为0时,
               boolean ranAction = false;        //调用barrier行为,并通知所有等待的线程
               try {
		   final Runnable command = barrierCommand;
                   if (command != null)
                       command.run(); //调用barrier行为
                   ranAction = true;   
                   nextGeneration(); //通知所有await的线程,使用condition对象的signlAll方法
                   return 0;
               } finally {
                   if (!ranAction)
                       breakBarrier();
               }
           }

            // loop until tripped, broken, interrupted, or timed out
            for (;;) {
                try {
                    if (!timed)                                                            //是否有超时操作
                        trip.await();                                                     //调用condition对象的await方法
                    else if (nanos > 0L)                                
                        nanos = trip.awaitNanos(nanos);
                } catch (InterruptedException ie) {
                    if (g == generation && ! g.broken) {
                        breakBarrier();
			throw ie;
		    } else {
			// We're about to finish waiting even if we had not
			// been interrupted, so this interrupt is deemed to
			// "belong" to subsequent execution.
			Thread.currentThread().interrupt();
		    }
                }

                if (g.broken)
                    throw new BrokenBarrierException();

                if (g != generation)
                    return index;

                if (timed && nanos <= 0L) {
                    breakBarrier();
                    throw new TimeoutException();
                }
            }
        } finally {
            lock.unlock();
        }
    }

java CyclicBarrier 实例

  • 0

    开心

    开心

  • 0

    板砖

    板砖

  • 0

    感动

    感动

  • 0

    有用

    有用

  • 0

    疑问

    疑问

  • 0

    难过

    难过

  • 0

    无聊

    无聊

  • 0

    震惊

    震惊

版权所有 IT知识库 CopyRight © 2009-2015 IT知识库 IT610.com , All Rights Reserved. 京ICP备09083238号