Java Spring:取消未来

时间:2014-07-07 01:48:23

标签: java spring

我有一种创造未来的方法:

@Service
public class TestService {
    @Async
    public Future<TestClass> testCancelFuture() throws InterruptedException  {
        TestClass testClass = new TestClass();
        testClass.loop();
        return new AsyncResult<TestClass>(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";
    }
}

我希望循环停止,因为我在启动后很快取消了未来。然而,循环继续。那么,我怎样才能在将来停止循环?

1 个答案:

答案 0 :(得分:3)

永远不会保证取消/中断正在运行的任务。请阅读Thread.interrupt() method description

  

如果在调用wait()时阻塞了这个线程,请等待(long),   或者等待(long,int)Object类或join()的方法,   join(long),join(long,int),sleep(long)或sleep(long,int)方法   这个类,然后它的中断状态将被清除   收到InterruptedException。

     

如果此线程在可中断的I / O操作中被阻止   然后通道将关闭,线程的中断状态   将被设置,线程将收到ClosedByInterruptException。

     

如果在选择器中阻塞了该线程,则线程中断   状态将被设置,它将立即从选择中返回   操作,可能具有非零值,就像选择器一样   唤醒唤醒方法。

     

如果以前的条件都没有,则该线程会中断   状态将被设置。

如果您的任务经常调用列出的其中一种方法,那么您获得更多响应取消的可能性就会提高。

否则线程可能会继续运行,就像忽略取消一样。改善这种情况的一种方法是将您的任务拆分为较小的块,以检查它是否应该在两者之间保持运行。