1
我有一個關於併發的項目,並且我的代碼的行爲有一些問題。我正在走一個文件樹來查找所有文件,如果我發現一個以.txt結尾的文件,我會向執行器提交一個任務。一個線程將打開文件並檢查文件中的最大數字。然後我創建一個對象,其中包含文件的路徑和該文件的最大編號。我將該對象追加到同步數組列表。但是當我運行代碼時,我的數組列表有時會有1個對象,或者5或112或64.每次運行它時都應該有140個對象。我希望你們知道問題是什麼。ExecutorService併發行爲不穩定和不穩定
public static List<Result> AllFiles(Path dir) throws InterruptedException{
final List<Result> resultlist = new ArrayList<Result>();
final List<Result> synclist;
synclist = Collections.synchronizedList(resultlist);
ExecutorService exec
= Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() + 1);
try {
Files.walk(dir).forEach(i -> {
String pathfile = i.getFileName().toString();
if (pathfile.contains(".txt")) {
exec.submit(() -> {
int high = findHighest(i);
ResultObj obj = new ResultObj(i, high);
synclist.add(obj);
});
}
});
exec.shutdown();
try {
exec.awaitTermination(1, TimeUnit.NANOSECONDS);
} catch (InterruptedException ex) {}
} catch (IOException ex) {}
System.out.println(synclist);
System.out.println(synclist.size());
return synclist;
}
謝謝你是對的,關於我在執行程序完成之前關閉它。我使用了CountDownLatch來確保每個線程都完成了。 – AwsGuy