求助 CompletableFuture 怎么取消其任务

查看 41|回复 2
作者:mengjisang   
查询到 cancel 方法其原型为
    /* ------------- Control and status methods -------------- */
    /**
     * If not already completed, completes this CompletableFuture with
     * a {@link CancellationException}. Dependent CompletableFutures
     * that have not already completed will also complete
     * exceptionally, with a {@link CompletionException} caused by
     * this {@code CancellationException}.
     *
     * @param mayInterruptIfRunning this value has no effect in this
     * implementation because interrupts are not used to control
     * processing.
     *
     * @return {@code true} if this task is now cancelled
     */
    public boolean cancel(boolean mayInterruptIfRunning) {
        boolean cancelled = (result == null) &&
            internalComplete(new AltResult(new CancellationException()));
        postComplete();
        return cancelled || isCancelled();
    }
mayInterruptIfRunning 参数实际并没有被用到,取消操作实际是软取消,并不会直接从线程池中进行取消操作,
实际测试发现 cancel 确实有问题,没有按照想象中快速取消超时任务,最终会导致线程池阻塞,不知道该怎么办
BBCCBB   
线程已经开始执行, 又没有可以被 interupt 的操作, 是取消不了的. 取消只是一个信号通知, 要代码里有响应才行.
线程跑到一半, 也不能直接把线程 destory 了不是?
mengjisang
OP
  
@BBCCBB 大概明白了,这个 cancel 方法,似乎就是设置了一下内部状态,然后抛出 CancellationException 异常
您需要登录后才可以回帖 登录 | 立即注册

返回顶部