9.3.3. 取消任务

通过Future.cancel()方法可以很方便的取消所有已提交的任务。通过对Thread.currentThread().isInterrupted()方法的调用可以在已经处于运行状态的任务里实现任务中断:

  1. public class CallableTask implements Callable<Long> {
  2. @RInject
  3. private RedissonClient redissonClient;
  4. @Override
  5. public Long call() throws Exception {
  6. RMap<String, Integer> map = redissonClient.getMap("myMap");
  7. Long result = 0;
  8. // map里包含了许多的元素
  9. for (Integer value : map.values()) {
  10. if (Thread.currentThread().isInterrupted()) {
  11. // 任务被取消了
  12. return null;
  13. }
  14. result += value;
  15. }
  16. return result;
  17. }
  18. }
  19. RExecutorService executorService = redisson.getExecutorService("myExecutor");
  20. Future<Long> future = executorService.submit(new CallableTask());
  21. // 或
  22. RFuture<Long> future = executorService.submitAsync(new CallableTask());
  23. // ...
  24. future.cancel(true);