java多线程之利用“CyclicBarrier”汇总结果

CyclicBarrier

A synchronization aid that allows a set of threads to all wait for each other to reach a common barrier point. CyclicBarriers are useful in programs involving a fixed sized party of threads that must occasionally wait for each other. The barrier is called cyclic because it can be re-used after the waiting threads are released.

A CyclicBarrier supports an optional Runnable command that is run once per barrier point, after the last thread in the party arrives, but before any threads are released. This barrier action is useful for updating shared-state before any of the parties continue.

CyclicBarrier

cyclicbarrier是一个同步助手,可以让一系列线程等待对方到达一个公共的节点,在程序里面CyclicBarriers主要是用来给固定大小的线程相互等待而设计的,值所以叫cyclic是因为它可以被反复复用。


package thread;

import java.util.concurrent.CyclicBarrier;

public class CyclicBarrierTestXiao {

	public static void main(String[] args){
		
		 TotalService totalService = new TotalService();   
	        CyclicBarrier barrier = new CyclicBarrier(5,  new TotalTask(totalService));   
	        // 实际系统是查出所有省编码code的列表,然后循环,每个code生成一个线程。   
	        new BillTask(new BillService(), barrier, "北京").start();   
	        new BillTask(new BillService(), barrier, "上海").start();   
	        new BillTask(new BillService(), barrier, "广西").start();   
	        new BillTask(new BillService(), barrier, "四川").start();   
	        new BillTask(new BillService(), barrier, "黑龙江").start();   
	     //   System.out.println(Thread.currentThread().getName());
	        
	      
	}

	
	
}

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

public class BillTask extends Thread{

	// 计费服务   
    private BillService billService;   
    private CyclicBarrier barrier;   
    // 代码,按省代码分类,各省数据库独立。   
    private String code;   
  
    BillTask(BillService billService, CyclicBarrier barrier, String code) {   
        this.billService = billService;   
        this.barrier = barrier;   
        this.code = code;   
    }   
  
    public void run() {   
        System.out.println("开始计算--" + code + "省--数据!");   
        billService.bill(code);   
        // 把bill方法结果存入内存,如ConcurrentHashMap,vector等,代码略   
        System.out.println(code + "省已经计算完成,并通知汇总Service!");   
        try {   
            // 通知barrier已经完成   
            barrier.await();   
        } catch (InterruptedException e) {   
            e.printStackTrace();   
        } catch (BrokenBarrierException e) {   
            e.printStackTrace();   
        }   
    }   
  
	
	
	
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值