情况如下:
我想使用多线程的方法将图像对应的一些特征向量存储到数据库中。 问题是,对于我给定的实现(我使用固定线程池),我无法保证输出的顺序。由于我给出了越来越多的数字作为将 vector 放置在数据库中的位置的索引,这会影响顺序并使其无法访问。
如果更多细节可以使问题更清楚:
- 我有很多 vector 存储为 csv 文件,每个图像/vector 1 个文件。
- 每个任务都会读取 csv 文件,计算一些其他索引
- 使用
Runnable
的实现来读取、计算索引等 - 调用
synchronized
方法在数据库中进行实际索引。
有没有办法强制输出的顺序与提交任务的顺序相同?换句话说,如果首先提交 vector i
,则应首先对 vector i
建立索引。
最佳答案
使用 ExecutorService 按顺序创建任务。
使用 executor.invokeAll 调用(启动)线程/任务。
按照任务提交的顺序使用 future.get() 获取任务结果。
ExecutorService executor = Executors.newFixedThreadPool(numberOfThread);
List<Task> threads = new ArrayList<>();
// create the threads
for (Integer key_ : dbIdList) {
threads.add(new Task(key_));
}
try {
//launch the threads
List<Future<String>> futures = executor.invokeAll(threads);
//read results
for (Future<String> future_ : futures) {
System.out.println(future_.get()); // this preserves the order of the tasks
}
} catch (Exception e) {
} finally {
//shut down
executor.shutdown();
}
执行任务的线程类:
class Task implements Callable<String> {
Integer dbId = null;
@Override
public String call() throws Exception {
//do whatever works needs to be done
return output;
}
public Task(int dbId_) {
this.dbId = dbId_;
}
}
关于java - 返回结果时保持提交任务的顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25996404/