繁体   English   中英

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

[英]Iterate through a thread with loop and process multiple results

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

目标是通过ImageProcessor().processLink urlList函数处理链接列表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");

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM