仅仅因为您调用并不意味着任务将自动停止。您必须在任务中执行一些工作以确保它将停止: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;
}
}
此外,正如其他文章所提到的:即使使用线程安全类也可以抛出,因为您从中获取的迭代器不是线程安全的,因此需要同步。增强的 for 循环使用迭代器,因此请注意:ConcurrentModificationException
Vector
Vector
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);
}
}