篱栅:CyclicBarrier

CountDownLatch的计数器只能使用一次,而CyclicBarrier【塞克丽克 百瑞尔】的计数器可以使用reset()方法重置。所以CyclicBarrier能处理更为复杂的业务场景。例如,如果计算发生错误,可以重置计数器,并让线程重新执行一次。
CyclicBarrier还提供其他有用的方法,比如getNumberWaiting方法可以获得Cyclic-Barrier阻塞的线程数量。isBroken()方法用来了解阻塞的线程是否被中断(thread.interrupt())。

package mytest;

import java.util.Map.Entry;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class CyclicbarrierTest implements Runnable {
    private static final int THREAD_COUNT = 4;

    private CyclicBarrier cyclicBarrier = new CyclicBarrier(THREAD_COUNT, this);//
    private static ExecutorService threadPool = Executors.newFixedThreadPool(THREAD_COUNT);
    private ConcurrentHashMap sheetBankWaterCount = new ConcurrentHashMap();

    private void count() {
        for (int i = 0; i < THREAD_COUNT; i++) {
            //线程池一跑起来,就停不下来了
            threadPool.execute(new Runnable() {
                @Override
                public void run() {
                    sheetBankWaterCount.put(Thread.currentThread().getName(), 1);
                    try {
                        cyclicBarrier.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } catch (BrokenBarrierException e) {
                        e.printStackTrace();
                    }
                    System.out.println("===");
                }
            });
        }
    }

    @Override
    public void run() {
        int result = 0;
        for (Entry sheet : sheetBankWaterCount.entrySet()) {
            result += sheet.getValue();
        }
        sheetBankWaterCount.put("result", result);
        System.out.println(result);
        try {
            Thread.sleep(10 * 1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        CyclicbarrierTest ct = new CyclicbarrierTest();
        ct.count();
        System.out.println("over");

    }
}

执行结果:

over 主线程继续执行
4 this线程在await之后执行
pool-1-thread-2 over this线程执行完了,await后面的代码再执行
pool-1-thread-1 over
pool-1-thread-4 over
pool-1-thread-3 over

你可能感兴趣的:(多线程)