gpt4 book ai didi

Java Spring : Cancelling a Future

转载 作者:行者123 更新时间:2023-11-29 05:21:16 25 4
gpt4 key购买 nike

我有一个创造 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com