循环遍历线程并处理多个结果

问题描述 投票:0回答:1

我正在尝试使用线程使我的程序并行运行某些部分并且很挣扎。

目标是通过urlList功能来处理链接列表,ImageProcessor().processLink。我要解决两个问题:

  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();
        }

    }
java multithreading java-8 scheduledexecutorservice
1个回答
0
投票

通过以下方法处理:

    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");
© www.soinside.com 2019 - 2024. All rights reserved.