java CyclicBarrier 实例

本文介绍了Java并发包中的CyclicBarrier类,通过一个具体的示例演示了如何使用CyclicBarrier来协调多个线程的执行流程。具体展示了如何让一组线程等待直到全部准备就绪后才一起执行某一任务。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

多个线程等待

 

多个线程共同的等待一个操作(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();
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值