我正在尝试使用线程使我的程序并行运行某些部分,但我正在努力。
目标是通过 ImageProcessor().processLink
函数处理链接列表 urlList
。我有两个问题正在尝试解决:
- 如何循环它,以便它使用池中的 N 个线程(在本例中为 10 个)?也就是说,我想一次处理 10 个链接。
- 上面的处理函数返回一个
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/