package com.yzu.zhang.thread.concurrent; import java.util.Map.Entry; import java.util.Random; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CyclicBarrier; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * 銀行流水處理服務類 * @date 2016年11月21日 */ public class BankCountService implements Runnable{ private int threadCount = 4; private Random random = new Random(); /** * 建立4個屏障類,都處理完以後執行當前類的run方法 */ private CyclicBarrier c = new CyclicBarrier(threadCount, this); private ExecutorService executor = Executors.newFixedThreadPool(threadCount); private ConcurrentHashMap<String, Integer> countMap = new ConcurrentHashMap<String, Integer>(); /** * 開啓線程池進行計算 */ private void count() { System.out.println(">>>>>開始計算>>>>>"); for (int i = 0; i < threadCount; i++) { executor.execute(new Runnable() { @Override public void run() { //計算當前sheet的銀行流水,模擬計算 int value = random.nextInt(10000); try { Thread.sleep(value); } catch (InterruptedException e1) { e1.printStackTrace(); } String threadName = Thread.currentThread().getName(); countMap.put(threadName, value); System.out.println("["+threadName+"]計算完成:"+value+", 等待彙總..."); //銀行流水計算完成,插入一個屏蔽,等待其餘線程的計算 try { c.await(); } catch (Exception e) { e.printStackTrace(); } } }); } } @Override public void run() { int total = 0; System.out.println("開始彙總..."); //彙總結果 for( String key : countMap.keySet() ) { total += countMap.get(key); } for(Entry<String,Integer> entry : countMap.entrySet()) { //total += entry.getValue().intValue(); } //將結果輸出 System.out.println("銀行總流水==="+total); //關閉線程池 if (executor != null) { executor.shutdown(); System.out.println(">>>>>計算結束>>>>>"); } } public static void main(String[] args) { BankCountService service = new BankCountService(); service.count(); } }
運行結果:java
>>>>>開始計算>>>>> [pool-1-thread-1]計算完成:750, 等待彙總... [pool-1-thread-2]計算完成:6426, 等待彙總... [pool-1-thread-4]計算完成:6538, 等待彙總... [pool-1-thread-3]計算完成:9430, 等待彙總... 開始彙總... 銀行總流水===23144 >>>>>計算結束>>>>>