即使使用executor.awaitTermination,方法也会在执行所有线程之前返回

时间:2015-04-25 22:09:35

标签: java multithreading concurrency parallel-processing executorservice

我有一个方法,它需要多个线程才能工作,然后相应地为每个线程执行run()方法,如下所示

public static Map<String, Integer> execute(int thread_count) {
        ExecutorService executor = Executors.newFixedThreadPool(thread_count);
        File folder = new File("logFiles/");       
        Collection<File> files = FileUtils.listFiles(folder, null, true);     
        for(File file : files){
            //For rach file in folder execute run()
            System.out.println(file.getName());
            executor.submit(new Runner((file.getAbsolutePath())));
        } 
        executor.shutdown();
        try {
            executor.awaitTermination(1, TimeUnit.DAYS);
        } catch (InterruptedException e) {
            System.out.println("Exception "+ e + " in CountLines.execute()");
        }
        for(Map.Entry<String, Integer> entry: Runner.lineCountMap.entrySet()){
            System.out.println(entry.getKey() + " : : " + entry.getValue());
        }
        return Runner.lineCountMap;// printing after all the threads finish executing
    }

run方法定义如下:

public void run() {
        try {
            count = countLines(file);//get number of lines in file
        } catch (IOException e) {
            System.out.println("Exception "+ e + " in Runner.run()");
        }
        //count number of lines in each file and add to map
        lineCountMap.put(file, count);
    }

由于我在上面的execute()方法中使用了executor.awaitTermination,我希望我的lineCountMap可以填充所有文件名作为键和行计数作为值。但似乎在执行所有线程之前返回了lineCountMap。

For the following files:
    logtest.2014­-07-­04.log
    logtest.2014­-07-­02.log
    logtest.2014­-07-­01.log
    logtest.2014­-07-­03.log

Expected Output:

lineCountMap:
/logtest.2014­-07-­01.log : : 4
/logtest.2014­-07-­02.log : : 8
/logtest.2014­-07-­03.log : : 2
/logtest.2014­-07-­04.log : : 1

Actual Output:

lineCountMap:
/logtest.2014­-07-­01.log : : 4
/logtest.2014­-07-­03.log : : 2
/logtest.2014­-07-­04.log : : 0

此处我缺少/logtest.2014-07-02.log 的内容,并且/logtest.2014-07-04.log的值在1时显示为0

1 个答案:

答案 0 :(得分:0)

lineCountMap更改为ConcurrentHashMap解决了这个问题。感谢Oliver Croisier在评论部分讨论的解决方案。