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

+1

'lineCountMap'是一個'ConcurrentHashMap'(就像它應該被多個線程併發訪問一樣),或者一個簡單的'java.util.HashMap'? –

+0

嗨@OlivierCroisier它是一個簡單的'java.util.HashMap'。每個線程都訪問'lineCountMap'中的獨立鍵,那麼我需要我的映射是併發嗎? –

+0

是的,你仍然需要在內存中正確發佈數據。將你的'HashMap'改爲'ConcurrentHashMap'並再次測試。 –

回答

0

lineCountMap更改爲ConcurrentHashMap解決了該問題。感謝Oliver Croisier在評論部分討論的解決方案。