From 095809d8713e4e366f2bac0c6d16ecef8bc728b2 Mon Sep 17 00:00:00 2001 From: zaker-666 <1075151259china@gmail.com> Date: Sun, 12 Jan 2020 16:10:22 +0800 Subject: [PATCH] =?UTF-8?q?=E5=AE=8C=E6=88=90=E4=BA=86=E4=B8=80=E7=A7=8D?= =?UTF-8?q?=E5=AD=97=E6=95=B0=E7=BB=9F=E8=AE=A1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../multithread/MultiThreadWordCount1.java | 46 ++++++++++++++++++- 1 file changed, 44 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/github/hcsp/multithread/MultiThreadWordCount1.java b/src/main/java/com/github/hcsp/multithread/MultiThreadWordCount1.java index 15c4aae..6af03da 100644 --- a/src/main/java/com/github/hcsp/multithread/MultiThreadWordCount1.java +++ b/src/main/java/com/github/hcsp/multithread/MultiThreadWordCount1.java @@ -1,12 +1,54 @@ package com.github.hcsp.multithread; +import java.io.BufferedReader; import java.io.File; +import java.io.FileReader; +import java.util.ArrayList; +import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; public class MultiThreadWordCount1 { // 使用threadNum个线程,并发统计文件中各单词的数量 - public static Map count(int threadNum, List files) { - return null; + public static Map count(int threadNum, List files) throws ExecutionException, InterruptedException { + ExecutorService executorService = Executors.newFixedThreadPool(threadNum); + Map countResult = new HashMap<>(); + List>> futures = new ArrayList<>(); + for (File file : files) { + futures.add(executorService.submit(() -> { + Map result = new HashMap<>(); + BufferedReader bufferedReader = new BufferedReader(new FileReader(file)); + String line = ""; + while ((line = bufferedReader.readLine()) != null) { + String[] split = line.split(" "); + for (String word : split) { + if (result.containsKey(word)) { + result.put(word, result.get(word) + 1); + } else { + result.put(word, 1); + } + } + } + return result; + })); + } + Map waitforMerge; + for (Future> future : futures) { + waitforMerge = future.get(); + mergeResulttoFinal(waitforMerge, countResult); + } + return countResult; + } + + private static void mergeResulttoFinal(Map waitforMerge, Map countResult) { + for (Map.Entry entry : waitforMerge.entrySet()) { + String word = entry.getKey(); + int i = countResult.getOrDefault(word, 0) + entry.getValue(); + countResult.put(word, i); + } } }