java - 使用循环迭代线程并处理多个结果

标签 java multithreading java-8 scheduledexecutorservice

我正在尝试使用线程使我的程序并行运行某些部分,但我正在努力。

目标是通过 ImageProcessor().processLink 函数处理链接列表 urlList。我有两个问题正在尝试解决:

  1. 如何循环它,以便它使用池中的 N 个线程(在本例中为 10 个)?也就是说,我想一次处理 10 个链接。
  2. 上面的处理函数返回一个File,我需要将其添加到一个数组fileList中。当涉及到多线程时,我将如何处理?

这是我到目前为止所得到的:

    ArrayList<String> urlList = new ArrayList<>(Arrays.asList(arr.split("\\r?\\n"))) ;
    ArrayList<File> fileList = new ArrayList<>();
    ExecutorService executor = Executors.newFixedThreadPool(10);

    //process the requested files
    for (int i = 0; i < urlList.size(); i++){
        Future<File> value = executor.submit(new Callable<File>() {
            @Override
            public File call(int i) throws IOException {
                return new ImageProcessor().processLink(urlList.get(i));
            }
        });

        try {
            fileList.add(value.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

    }

最佳答案

让它与以下内容一起工作:

    ArrayList<String> urlList = new ArrayList<>(Arrays.asList(arr.split("\\r?\\n"))) ;
    ArrayList<File> fileList = new ArrayList<>();

    ExecutorService executor = Executors.newFixedThreadPool(THREAD_SIZE);
    List<Future<File>> futures = new ArrayList<>();

    for (int i = 0; i < urlList.size(); i++) {
        ImageProcessor proc = new ImageProcessor(urlList.get(i));
        final Future<File> future = executor.submit(proc);
        futures.add(future);
    }

    try {
        executor.awaitTermination(5, TimeUnit.SECONDS);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    for (int i = 0; i < futures.size(); i++)
    {
        Future<File> result = futures.get(i);
        try {
            fileList.add(result.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }
    executor.shutdown();
    while (!executor.isTerminated()) { }
    System.out.println("Finished all threads");

关于java - 使用循环迭代线程并处理多个结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60768064/

相关文章:

java - Mac 在命令终端和系统偏好设置中报告不同版本的 Java

java - 如何使用spring批处理在postgresql中执行存储过程?

java - 关闭 Java 8 流

java - 在 Linux (Ubuntu) 中在 java 7 和 java 8 之间切换的推荐方法是什么?

java - Hibernate 5.2.11 - 多个同时 Featch.Eager

python - 在主线程中使用 KeyboardException 中断 Python 中的线程

java - 是 webRTC 原生 Android 应用程序所需的特定线程模型

java - 如何计算多个线程完成执行的总时间?

java - 为什么 Temporal 不在 Java 8 jsr310 中扩展 Comparable

java - 在Web项目中哪里创建了ApplicationContext?