仅仅因为你调用并不意味着任务会自动停止cancel()
。Future
您必须在任务中做一些工作以确保它会停止:
- 使用
cancel(true)
以便向任务发送中断。
- 处理
InterruptedException
。如果您的任务中的某个函数抛出一个InterruptedException
,请确保您在捕获异常后尽快优雅地退出。
- 定期检查
Thread.currentThread().isInterrupted()
任务是否进行连续计算。
例如:
class LongTask implements Callable<Double> {
public Double call() {
// Sleep for a while; handle InterruptedException appropriately
try {
Thread.sleep(10000);
} catch (InterruptedException ex) {
System.out.println("Exiting gracefully!");
return null;
}
// Compute for a while; check Thread.isInterrupted() periodically
double sum = 0.0;
for (long i = 0; i < 10000000; i++) {
sum += 10.0
if (Thread.currentThread().isInterrupted()) {
System.out.println("Exiting gracefully");
return null;
}
}
return sum;
}
}
此外,正如其他帖子所提到的:ConcurrentModificationException
即使使用线程安全Vector
类也可以抛出,因为您从中获取的迭代器Vector
不是线程安全的,因此需要同步。增强的 for 循环使用迭代器,因此请注意:
final Vector<Double> vector = new Vector<Double>();
vector.add(1.0);
vector.add(2.0);
// Not thread safe! If another thread modifies "vector" during the loop, then
// a ConcurrentModificationException will be thrown.
for (Double num : vector) {
System.out.println(num);
}
// You can try this as a quick fix, but it might not be what you want:
synchronized (vector) { // "vector" must be final
for (Double num : vector) {
System.out.println(num);
}
}