循环通过 Futures - 你应该先检查 isDone 吗?
Looping Through Futures - Should you check isDone first?
我有一份期货清单。
List<Future> futures = new ArrayList<Future>();
futures.add(task1());
futures.add(task2());
这两种获取结果的方法有区别吗?
// Option 1
for (Future future : futures) {
results.add(future.get());
}
// Option 2
boolean incompleteFound;
do {
incompleteFound = false;
for (Future future : futures) {
if (!future.isDone()) {
incompleteFound = true;
}
}
} while (incompleteFound);
for (Future future : futures) {
results.add(future.get());
}
我假设在 Option 1
中 get
调用处于阻塞状态,这不会影响后台的期货处理。我的假设是否正确?
正确。做第一个。等待一个未来的结果不会影响其他任何结果(甚至不会影响您正在等待的结果)。
第二个不仅没有必要而且超级浪费。你现在有一个繁忙的循环,而不是将 CPU 交给其他线程,它会无缘无故地旋转 CPU 消耗 CPU 个周期。
是的,不影响,以后所有任务在background.Refer中并行运行:https://javarevisited.blogspot.com/2015/01/how-to-use-future-and-futuretask-in-Java.html#axzz5rLieL6lf
我有一份期货清单。
List<Future> futures = new ArrayList<Future>();
futures.add(task1());
futures.add(task2());
这两种获取结果的方法有区别吗?
// Option 1
for (Future future : futures) {
results.add(future.get());
}
// Option 2
boolean incompleteFound;
do {
incompleteFound = false;
for (Future future : futures) {
if (!future.isDone()) {
incompleteFound = true;
}
}
} while (incompleteFound);
for (Future future : futures) {
results.add(future.get());
}
我假设在 Option 1
中 get
调用处于阻塞状态,这不会影响后台的期货处理。我的假设是否正确?
正确。做第一个。等待一个未来的结果不会影响其他任何结果(甚至不会影响您正在等待的结果)。
第二个不仅没有必要而且超级浪费。你现在有一个繁忙的循环,而不是将 CPU 交给其他线程,它会无缘无故地旋转 CPU 消耗 CPU 个周期。
是的,不影响,以后所有任务在background.Refer中并行运行:https://javarevisited.blogspot.com/2015/01/how-to-use-future-and-futuretask-in-Java.html#axzz5rLieL6lf