- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个创造 future 的方法:
@Service
public class TestService {
@Async
public Future<TestClass> testCancelFuture() throws InterruptedException {
TestClass testClass = new TestClass();
testClass.loop();
return new AsyncResult<TestClass>(testClass);
}
}
这是我的测试类
public class TestClass {
public void loop() throws InterruptedException {
for (int i=0; i<100; i++) {
System.out.println("[" + i + "] loop");
Thread.sleep(1000);
}
}
}
现在,我调用方法 testCancelFuture 并取消它:
@Controller
@RequestMapping("/test")
public class TestController() {
@Autowired
TestService testService;
@RequestMapping(method = RequestMethod.GET)
public String testMethod () throws InterruptedException {
Future<TestClass> test = testService.testCancelFuture();
test.cancel(true);
return "test";
}
}
我希望循环停止,因为我在启动它后不久就取消了 future 。然而,循环继续进行。那么,我以后该如何停止循环呢?
最佳答案
无法保证取消/中断正在运行的任务。阅读Thread.interrupt()
method description :
If this thread is blocked in an invocation of the wait(), wait(long), or wait(long, int) methods of the Object class, or of the join(), join(long), join(long, int), sleep(long), or sleep(long, int), methods of this class, then its interrupt status will be cleared and it will receive an InterruptedException.
If this thread is blocked in an I/O operation upon an interruptible channel then the channel will be closed, the thread's interrupt status will be set, and the thread will receive a ClosedByInterruptException.
If this thread is blocked in a Selector then the thread's interrupt status will be set and it will return immediately from the selection operation, possibly with a non-zero value, just as if the selector's wakeup method were invoked.
If none of the previous conditions hold then this thread's interrupt status will be set.
如果您的任务经常调用列出的这些方法之一,那么您将更有可能获得响应更快的取消。
否则线程可能会继续运行,就好像取消被忽略了一样。改进这一点的一种方法是将您的任务分成更小的 block ,检查它是否应该在它们之间继续运行。
关于Java Spring : Cancelling a Future,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24602052/
我是一名优秀的程序员,十分优秀!