package org.code.pomelo.concurrent.thread.common;

import java.util.Map;
import java.util.concurrent.*;

/**
 * Created by ruyin on 2017/11/28.
 *
 *
 * 使用线程池创建4个线程,分别计算每个sheet里的数据
 */
public class BankWaterService implements Runnable {

    /**
     * 设置4个屏障,处理完之后执行当前类的run()方法
     *
     * */
    private CyclicBarrier barrier = new CyclicBarrier(4,this);

    /**
     * 假设只有4个sheet,启动4个线程
     *
     * */
    private Executor executor = Executors.newFixedThreadPool(4);

    /**
     * 保存每个sheet计算出的流水结果
     *
     * */
    private ConcurrentHashMap<String,Integer> sheetBankCountWater = new ConcurrentHashMap<>();

    private void count(){
        for (int i = 0; i < 4; i++){
            executor.execute(() -> {
                //模拟数据
                sheetBankCountWater.put(Thread.currentThread().getName(),1);

                try {
                    barrier.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }
            });
        }
    }

    @Override
    public void run() {
        int result = 0;

        //sheetBankCountWater.compute("result",(k,v) -> {v = sheetBankCountWater.get(k) + v;return v;});

        for (Map.Entry<String,Integer> sheet:sheetBankCountWater.entrySet()){
            result += sheet.getValue();
        }

        sheetBankCountWater.put("result",result);
        System.out.println(sheetBankCountWater.get("result"));
    }

    public static void main(String[] args) {
        BankWaterService service = new BankWaterService();
        service.count();
    }
}
