0
我有需要的线程数工作,然后的方法相应地执行每个线程的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
}
而运行方法被定义如下:
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);
}
正如我已经使用executor.awaitTermination在execute()方法的上方,我期待我lineCountMap与所有filesnames作为密钥和行计数作为值来填充。但似乎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值内容显示0时为1
'lineCountMap'是一个'ConcurrentHashMap'(就像它应该被多个线程并发访问一样),或者一个简单的'java.util.HashMap'? –
嗨@OlivierCroisier它是一个简单的'java.util.HashMap'。每个线程都访问'lineCountMap'中的独立键,那么我需要我的映射是并发吗? –
是的,你仍然需要在内存中正确发布数据。将你的'HashMap'改为'ConcurrentHashMap'并再次测试。 –