标签:
import java.util.concurrent.BrokenBarrierException; import java.util.concurrent.CyclicBarrier; public class CyclicBarrierLearn { public static void main(String[] args) { final float x = 0.2f; int numberOfTerms = 10; final float[] arr = new float[numberOfTerms]; //一旦barrier获得CPU,必须等到该线程执行完毕,否则CPU不会被释放,之所以出现这中情况 //是因为barrierAction这个以一种回调接口的形式暴漏出来,其实底层的实现机制已经通过模板指定好了规则,当执行该方法之后 //才统一唤醒与之相关的全部线程 CyclicBarrier barrier = new CyclicBarrier(numberOfTerms, new Runnable() { @Override public void run() { float sum = 0; for (int i = 0; i < arr.length; i++) { sum += arr[i]; } System.out.println("ln (1 - " + x + ") ≈ " + -sum); } }); for (int i = 0; i < numberOfTerms; i++) { new Thread(new TermCacl(barrier, i, x, arr)).start(); } } } class TermCacl implements Runnable { private int termIndex; private CyclicBarrier barrier; private float x; private float[] arr; public TermCacl(CyclicBarrier barrier, int termIndex, float x, float[] arr) { this.barrier = barrier; this.termIndex = termIndex; this.x = x; this.arr = arr; } @Override public void run() { try { arr[termIndex] = (float) (Math.pow(x, termIndex + 1) / (termIndex + 1)); barrier.await(); System.out.println(Thread.currentThread().getName() + termIndex); } catch (InterruptedException e) { e.printStackTrace(); } catch (BrokenBarrierException e) { e.printStackTrace(); } } }
标签:
原文地址:http://www.cnblogs.com/zhaojunyang/p/5067884.html