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