huangjs:
私は、スレッドプールを使用して複数のファイルを読みたいが、私は失敗しました。
@Test
public void test2() throws IOException {
String dir = "/tmp/acc2tid2999928854413665054";
int[] shardIds = new int[]{1, 2};
ExecutorService executorService = Executors.newFixedThreadPool(2);
for (int id : shardIds) {
executorService.submit(() -> {
try {
System.out.println(Files.readAllLines(Paths.get(dir, String.valueOf(id)), Charset.forName("UTF-8")));
} catch (IOException e) {
e.printStackTrace();
}
});
}
}
上記は、私が書いた簡単な例です。それは私の目的を達することができません。
System.out.println(Files.readAllLines(
Paths.get(dir, String.valueOf(id)), Charset.forName("UTF-8")));
この行は実行されず、何の警告はありませんでした。私はなぜか分からないのですか?
タンタル:
あなたは完全にタスクを待っている前にテストを終了し、その後、実行すべきタスクを提出しています。ExecutorService::submit
将来的に実行されるタスクを送信し、すぐに戻ります。したがって、あなたは、forループは終了する二つのタスクを提出し、作業前にテスト関数が返すが完了するまでに時間を過ごしました。
あなたは呼び出してみてくださいExecutorService::shutdown
executorがすべてのタスクが提出されていることを知っているように、forループの後に。その後、使用ExecutorService::awaitTermination
の作業が完了するまでブロックします。
例えば:
@Test
public void test2() throws IOException {
String dir = "/tmp/acc2tid2999928854413665054";
int[] shardIds = new int[]{1, 2};
ExecutorService executorService = Executors.newFixedThreadPool(2);
for (int id : shardIds) {
executorService.submit(
() -> {
try {
System.out.println(Files.readAllLines(Paths.get(dir, String.valueOf(id)), Charset.forName("UTF-8")));
} catch (IOException e) {
e.printStackTrace();
}
});
}
executorService.shutdown();
executorService.awaitTermination(60, TimeUnit.SECONDS); //Wait up to 1 minute for the tasks to complete
}