Java CyclicBarrier

一 介绍

CyclicBarrier是一个同步辅助类,在JDK1.5中被添加,它允许一组线程互相等待,直到到达某个公共屏障点 (common barrier point)。因为该 barrier 在释放等待线程后可以重用,所以称它为循环 的 barrier。

注意比较CountDownLatch和CyclicBarrier:
1.CountDownLatch的作用是允许1或N个线程等待其他线程完成执行;而CyclicBarrier则是允许N个线程相互等待。

2.CountDownLatch的计数器无法被重置;CyclicBarrier的计数器可以被重置后使用,因此它被称为是循环的barrier。


二 类结构

1.构造方法
CyclicBarrier(int parties)
       Creates a new CyclicBarrier that will trip when the given number of parties (threads) are waiting upon it, and does not perform a predefined action when the barrier is tripped.
CyclicBarrier(int parties, Runnable barrierAction)
       Creates a new CyclicBarrier that will trip when the given number of parties (threads) are waiting upon it, and which will execute the given barrier action when the barrier is tripped, performed by the last thread entering the barrier.

2.成员方法

Modifier and Type Method and Description
int await() Waits until all parties have invoked await on this barrier.
int await(long timeout, TimeUnit unit)Waits until all parties have invoked await on this barrier, or the specified waiting time elapses.
int getNumberWaiting()Returns the number of parties currently waiting at the barrier.
int getParties()Returns the number of parties required to trip this barrier.
boolean isBroken()Queries if this barrier is in a broken state.
void reset() Resets the barrier to its initial state.


三 使用示例

demo1
新建5个线程,当这5个线程达到一定的条件时,它们才继续往后运行。

package com.ricky.java.concurrent;

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

public class CyclicBarrierDemo {
	
	private static final int PARTIES = 5;
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		
		CyclicBarrier cb = new CyclicBarrier(PARTIES);
		
		ExecutorService pool = Executors.newFixedThreadPool(PARTIES);
		
		for(int i=0;i<PARTIES;i++){
			
			pool.execute(new Worker(i,cb));
		}
		
		//执行完毕后关闭
		pool.shutdown();
	}
	
	private static class Worker implements Runnable{
		private int tId;
		private CyclicBarrier cb;
		public Worker(int tId,CyclicBarrier cb){
			this.tId = tId;
			this.cb = cb;
		}
		@Override
		public void run() {
			
			System.out.println("Thread "+tId+" run...");
			
			try {
				cb.await();
			} catch (InterruptedException e) {
				e.printStackTrace();
			} catch (BrokenBarrierException e) {
				e.printStackTrace();
			}
			
			System.out.println("Thread "+tId+" continue...");
		}
		
	}

}

执行结果:

Thread 0 run...
Thread 2 run...
Thread 1 run...
Thread 3 run...
Thread 4 run...
Thread 0 continue...
Thread 1 continue...
Thread 2 continue...
Thread 3 continue...
Thread 4 continue...


主线程中新建了5个线程,所有的这些线程都调用cb.await()等待。这5个线程一直等待,直到cb中所有线程都达到barrier时,这些线程才继续运行!


demo2
新建5个线程,当这5个线程达到一定的条件时,执行某项任务。

package com.ricky.java.concurrent;

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

public class CyclicBarrierDemo2 {
	
	private static final int PARTIES = 5;
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		
		CyclicBarrier cb = new CyclicBarrier(PARTIES, new BarrierAction());
		
		ExecutorService pool = Executors.newFixedThreadPool(PARTIES);
		
		for(int i=0;i<PARTIES;i++){
			
			pool.execute(new Worker(i,cb));
		}
		
		//执行完毕后关闭
		pool.shutdown();
	}
	
	private static class BarrierAction implements Runnable{

		@Override
		public void run() {
			
			System.out.println("barrierAction run...");
		}
		
	}
	
	private static class Worker implements Runnable{
		private int tId;
		private CyclicBarrier cb;
		public Worker(int tId,CyclicBarrier cb){
			this.tId = tId;
			this.cb = cb;
		}
		@Override
		public void run() {
			
			System.out.println("Thread "+tId+" run...");
			
			try {
				cb.await();
			} catch (InterruptedException e) {
				e.printStackTrace();
			} catch (BrokenBarrierException e) {
				e.printStackTrace();
			}
			
			System.out.println("Thread "+tId+" continue...");
		}
		
	}

}

执行结果:

Thread 1 run...
Thread 2 run...
Thread 3 run...
Thread 0 run...
Thread 4 run...
barrierAction run...
Thread 4 continue...
Thread 0 continue...
Thread 3 continue...
Thread 1 continue...
Thread 2 continue...


主线程中新建了5个线程,这5个线程都调用cb.await()等待。这5个线程一直等待,直到cb中所有线程都达到barrier时,执行新建cb时注册的Runnable任务。




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值