import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; public class CSVProcessing { public static void main(String[] args) { List<String> filePaths = List.of("file1.csv", "file2.csv", "file3.csv"); ExecutorService executorService = Executors.newFixedThreadPool(filePaths.size()); List<List<String>> results = new ArrayList<>(); try { results = executorService.invokeAll( filePaths.stream() .map(filePath -> (Runnable) () -> { List<String> lines = CSVeed.parse(filePath); return lines.stream() .map(line -> { return line; }) .collect(Collectors.toList()); }) .collect(Collectors.toList()) ).stream() .map(future -> { try { return future.get(); } catch (Exception e) { e.printStackTrace(); return new ArrayList<String>(); } }) .collect(Collectors.toList()); } catch (InterruptedException e) { e.printStackTrace(); } finally { executorService.shutdown(); try { if (!executorService.awaitTermination(5, TimeUnit.SECONDS)) { executorService.shutdownNow(); } } catch (InterruptedException e) { executorService.shutdownNow(); Thread.currentThread().interrupt(); } } List<String> mergedResults = results.stream().flatMap(List::stream).collect(Collectors.toList()); // ... } }


上一篇:
下一篇:
切换中文