Java CyclicBarrier学习

CyclicBarrier用于处理任务拆分,计算,等待计算全部完成,然后合并计算的场景,Future,CountDownLatch可以实现类似的场景。

 

package multithread.cycle;

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

/**
 * 计算1^2 + 2^2 + 3^2 + ...
 * 
 * @author lemzhang
 * 
 */
public class TestCycle {
	private final CyclicBarrier cb;
	private final BlockingQueue result;
	private int total = 0;

	public TestCycle(int n) {
		result = new ArrayBlockingQueue(n);
		final long start = System.currentTimeMillis();
		cb = new CyclicBarrier(n, new Runnable() {
			@Override
			public void run() {
				for (Long i : result) 
					total += i;
				long end = System.currentTimeMillis();
				System.out.printf("我计算好了,花了%d毫秒,结果是%d", (end - start), getResult());
			}
		});
	}

	public void calculate() {
		for (int i = 1; i <= cb.getParties(); i++) {
			new Thread(new Calculate(i)).start();
		}
	}

	public long getResult() {
		return total;
	}

	class Calculate implements Runnable {
		private int n;
		Calculate(int n) {
			this.n = n;
		}
		@Override
		public void run() {
			result.offer((long) Math.pow(n, 2));
			try {
				cb.await();
			} catch (InterruptedException e) {
				e.printStackTrace();
			} catch (BrokenBarrierException e) {
				e.printStackTrace();
			} 
		}
	}

	public static void main(String[] args) {
		 TestCycle t = new TestCycle(200);
		 t.calculate();
	}
}

 

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