如何使用线程池来读取多个文件?

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::shutdownfor循环后,让执行者知道的所有任务已提交。然后使用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
    }

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章