JavaSpring:取消未来
我有一种创造未来的方法:JavaSpring:取消未来,java,spring,Java,Spring,我有一种创造未来的方法: @Service public class TestService { @Async public Future<TestClass> testCancelFuture() throws InterruptedException { TestClass testClass = new TestClass(); testClass.loop(); return new AsyncResult&l
@Service
public class TestService {
@Async
public Future<TestClass> testCancelFuture() throws InterruptedException {
TestClass testClass = new TestClass();
testClass.loop();
return new AsyncResult<TestClass>(testClass);
}
}
@服务
公共类测试服务{
@异步的
public Future testCancelFuture()抛出InterruptedException{
TestClass TestClass=新的TestClass();
testClass.loop();
返回新的异步结果(testClass);
}
}
这是我的测试课
public class TestClass {
public void loop() throws InterruptedException {
for (int i=0; i<100; i++) {
System.out.println("[" + i + "] loop");
Thread.sleep(1000);
}
}
}
公共类TestClass{
public void loop()引发InterruptedException{
对于(int i=0;i而言,永远不能保证取消/中断正在运行的任务。请阅读:
如果该线程在wait()的调用中被阻塞,wait(long),
或对象类或join()的wait(long,int)方法,
join(long)、join(long,int)、sleep(long)或sleep(long,int)方法
则其中断状态将被清除,并且
接收中断异常
如果此线程在I/O操作中因可中断事件而被阻塞
然后通道将关闭,线程的中断状态
将被设置,并且线程将接收ClosedByInterruptException
如果该线程在选择器中被阻塞,则该线程的中断
将设置状态,并立即从选择返回
操作,可能使用非零值,就像选择器
已调用唤醒方法
如果前面的条件都不成立,那么这个线程的中断
将设置状态
如果您的任务定期调用列出的其中一种方法,那么您得到响应性更强的取消的可能性更大
否则,线程可能会像忽略取消一样继续运行。一种改进方法是将任务分成更小的块,检查它是否应该在这两个块之间继续运行。发布cancel()
方法的codecancel()一旦启动就很难保证。您的代码不会编译为线程。sleep
被声明为引发异常。您需要处理它。还可以查看可能的重复:检查Spring的源代码:AsyncResult。取消(布尔)
不执行任何操作,并且始终返回false
,这意味着无法取消任务
@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";
}
}