java同步例子之CyclicBarrier

它允许一组线程互相等待,直到到达某个公共屏障点,barrier 在释放等待线程后可以重用,所以称它为循环 的 barrier。
package concurrent;

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

/**
 * 允许一组线程互相等待,直到到达某个公共屏障点
 * @author user
 *
 */
public class CyclicBarrierTest {
	
	private int[] numArray = new int[5];
	
	private final CyclicBarrier barrier = new CyclicBarrier(5, new Runnable() {		
		@Override
		public void run() {
			int sum = 0;
			for(int i = 0; i < numArray.length; i++){
				sum += numArray[i];
			}
			System.err.println(sum);
			
		}
	});
	
	public void start(){
		for(int i = 0; i < numArray.length; i++){
			final int j = i;
			new Thread(new Runnable() {				
				@Override
				public void run() {
					numArray[j] = j + 1;
					try {
						barrier.await();
					} catch (InterruptedException e) {
						e.printStackTrace();
					} catch (BrokenBarrierException e) {
						e.printStackTrace();
					}
				}
			}).start();
		}
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		CyclicBarrierTest test = new CyclicBarrierTest();
		test.start();
	}

}

你可能感兴趣的:(java,Cyclicbarrier,Concurrent)