1
동시성에 대한 프로젝트가 있으며 코드 작동에 문제가 있습니다. 나는 모든 파일을 찾기 위해 파일 트리를 걷고 있는데 .txt로 끝나는 파일을 찾으면 나는 집행자에게 작업을 제출한다. 스레드가 파일을 열고 파일에서 가장 큰 숫자를 확인합니다. 그런 다음 파일의 경로와 해당 파일의 가장 큰 번호를 포함하는 개체를 만듭니다. 동기화 된 arraylist에 객체를 추가합니다. 그러나 코드를 실행할 때 arraylist는 때때로 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