Java 即使在调用取消方法后线程也没有停止?

Java thread not stopping even after calling cancel method?

public class my {
public static void main(String[] args) throws InterruptedException {
    SomeService service = new SomeService();

    CompletableFuture<Void> async = CompletableFuture.runAsync(() -> {
        try (AutoClosableResource<SomeService> resource = new AutoClosableResource<>(service, service::disconnect)) {
            resource.get().connect();
            int i = 0;
            while (true) {
                System.out.println("--------------inside while" + i);
                Thread.sleep(500);
                i++;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    });
    System.out.println("ouside while");
    Thread.sleep(2500);
    async.cancel(true);
    System.out.println(async.isCompletedExceptionally());
    Thread.sleep(1000);

}

public static class SomeService {
    public void connect() {
        System.out.println("connect");
    }

    public Integer disconnect() {
        System.out.println("disconnect");
        return null;
    }
}

public static class AutoClosableResource<T> implements AutoCloseable {

    private final T resource;
    private final Runnable closeFunction;

    private AutoClosableResource(T resource, Runnable closeFunction) {
        this.resource = resource;
        this.closeFunction = closeFunction;
    }

    public T get() {
        return resource;
    }

    @Override
    public void close() throws Exception {
        closeFunction.run();
    }
}

}

-------output--------


ouside while connect
--------------inside while0
--------------inside while1
--------------inside while2
--------------inside while3
--------------inside while4 true
--------------inside while5
--------------inside while6

问:为什么线程仍然 运行 并且打印 isCompletedExceptionally() = true 即使我手动停止它,async.cancel(true);

简答: 线程仍然是 运行 因为 CompletableFuture cancel 方法对 runAsync 进程没有影响,并且不会中断线程。

async.isCompletedExceptionally() returns 正确,因为取消抛出异常 CompletionException

详情:

来自 javadoc 的有关取消方法的信息:

If not already completed, completes this CompletableFuture with a CancellationException. Dependent CompletableFutures that have not already completed will also complete exceptionally, with a CompletionException caused by this CancellationException

此方法仅完成CompletableFuture 和方法,这些方法依赖于等待得到由此CancellationException 引起的CompletionException 的结果。方法不应用于中断线程,而应用于完成依赖方法的工作。未来将异常完成

你应该在进程中使用这个方法,在那里你做了一些工作,并决定取消它

因此,您的线程继续工作并因 System.exit() 而终止 查看 public static ForkJoinPool commonPool() javadoc

Returns the common pool instance. This pool is statically constructed; its run state is unaffected by attempts to shutdown or shutdownNow. However this pool and any ongoing processing are automatically terminated upon program System.exit. Any program that relies on asynchronous task processing to complete before program termination should invoke commonPool().awaitQuiescence, before exit.