java CyclicBarrier

CyclicBarrier   api的描述如下,
* 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.

CyclicBarrier是所有的线程都必须相互等待,达到公共的屏障点,在释放屏障点后是可以重复使用的,这一点比

CountDownLatch好一些

CyclicBarrier包含的方法如下:

java CyclicBarrier_第1张图片

 

 

 

package com.ls.skynet;

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

public class CyclicBarrierTest {
    public static void main(String[] args) {
        //朋友约好一起出发去旅行
        final CyclicBarrier cyclicBarrier = new CyclicBarrier(3);
        for(int i=0;i<3;i++){
            Thread t = new Thread(new TravelThread(cyclicBarrier));
            t.start();

                System.out.println("有多少个wait parties"+cyclicBarrier.getNumberWaiting());


        }
        cyclicBarrier.reset();
        System.out.println(cyclicBarrier.getNumberWaiting());
        System.out.println(cyclicBarrier.getParties());
    }

    public static class TravelThread implements Runnable{
         final CyclicBarrier cyc ;
         TravelThread(CyclicBarrier cyc ){
            this.cyc = cyc;
        }
        public void run(){
            try {
                cyc.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (BrokenBarrierException e) {
                e.printStackTrace();
            }
        }
    }
}

 

java CyclicBarrier_第2张图片

java CyclicBarrier_第3张图片

 

 

你可能感兴趣的:(java)