多线程
- /*
- * To change this license header, choose License Headers in Project Properties.
- * To change this template file, choose Tools | Templates
- * and open the template in the editor.
- */
- package 多线程.结果汇总;
- import java.util.Map.Entry;
- import java.util.concurrent.BrokenBarrierException;
- import java.util.concurrent.ConcurrentHashMap;
- import java.util.concurrent.CyclicBarrier;
- import java.util.concurrent.Executor;
- import java.util.concurrent.Executors;
- /**
- *
- * @author aixiaolong
- */
- public class BankWaterService implements Runnable {
- private CyclicBarrier c = new CyclicBarrier(4, this);
- private Executor executor = Executors.newFixedThreadPool(4);
- private ConcurrentHashMap<String, Integer> sheetBankWaterCount = new ConcurrentHashMap<>();
- private void count() {
- System.out.println("count start..........");
- for (int i = 0; i < 4; i++) {
- executor.execute(new Runnable() {
- public void run() {
- sheetBankWaterCount.put(Thread.currentThread().getName(), 1);
- try {
- c.await();
- } catch (InterruptedException ex) {
- ex.printStackTrace();
- } catch (BrokenBarrierException ex) {
- ex.printStackTrace();
- }
- System.out.println("11111");
- }
- });
- }
- System.out.println("count end..........");
- }
- public void run() {
- System.out.println("");
- int result = 0;
- for (Entry<String, Integer> sheet : sheetBankWaterCount.entrySet()) {
- result += sheet.getValue();
- }
- sheetBankWaterCount.put("result", result);
- System.out.println(result);
- }
- public static void main(String[] args) {
- BankWaterService bankWatercount = new BankWaterService();
- bankWatercount.count();
- }
- }
来源: https://www.oschina.net/code/snippet_2886591_58642