java - 导致取消任务失败的其他原因是什么?

标签 java multithreading future

"boolean cancel(boolean mayInterruptIfRunning) Attempts to cancel execution of this task. This attempt will fail if the task has already completed, has already been cancelled, or could not be cancelled for some other reason"

https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Future.html#cancel(boolean)

除了上面列出的原因,还有什么原因导致取消任务失败? 另外,如果任务运行如下代码,是否可以取消?

while(true)
{
;
}

最佳答案

您发布的 while 循环将是不可取消代码的一个示例,因为它不响应中断。

阻塞监听套接字的代码也可能无法处理中断。即使代码因 InterruptedIOException 超时,如果您在未设置中断标志的情况下吞下异常,则代码可能无法处理中断。

所以 TLDR:1) 阻塞 IO 的代码 2) 忽略中断如何工作的代码。或两者的结合。

关于java - 导致取消任务失败的其他原因是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39239500/

相关文章:

java - BufferedImage中RGB数据的快速加载和绘制

java - 在jsp中包含一个cpp文件

c# - 响应式扩展、锁和线程

c++ - __thread 说明符在 C++ 类中不起作用

scala - Scala 中的 Futures 真的有用吗?

scala - 尝试解析 Future 响应时出了什么问题?

java - selenium webdriver 模式对话框 java

java - 如何解决需要静态方法的 getter 问题?

java - 在 Java 中运行时如何阻止主线程消耗完整的 CPU

java - ExecutorService 的 future 任务并未真正取消