FutureTask.cancle(true) 无法终止任务执行

futureTask.cancle(true) 是可以强行取消任务执行的,

但有一个前提条件:

futureTask中必须能抛出 InterruptedException 异常,

最常见的方式就是 task中 进行 Thread.sleep,

但一定要注意:一定不要try-catch  Thread.sleep 抛出的 InterruptedException ,一定要让 InterruptedException  能抛出来。

    @Async
    public Future<String> run() throws InterruptedException {
        long sleep = random.nextInt(10000);
        log.info(Thread.currentThread().getId() + ":开始任务,需耗时:" + sleep + "毫秒");
        //@point: 此处不能捕获异常,不然futureTask.cancle(true) 无法让任务取消
//        try {
        Thread.sleep(sleep);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
        log.info(Thread.currentThread().getId() + ":完成任务");
        return new AsyncResult<>("test");
    }

 

如果futureTask中没有使用sleep ,也可以考虑用 Thread.currentThread().isInterrupted() 监控task线程的中断状态 来进行终止 任务。

    @Async
    public Future<String> run() throws InterruptedException {
        do{
            System.out.println("...");
        }while(!Thread.currentThread().isInterrupted());
        return new AsyncResult<>("test");
    }

 

posted on 2019-08-17 16:34  HB1  阅读(3514)  评论(0)    收藏  举报

导航