スレッドプールを使用して複数のファイルを読むにはどのように?

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::shutdownexecutorがすべてのタスクが提出されていることを知っているように、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
    }

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=199385&siteId=1