gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 17:52:48 26 4
gpt4 key购买 nike

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

目标是通过 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com