【发布时间】:2020-03-13 19:50:57
【问题描述】:
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);
【问题讨论】:
-
the documentation of
cancel是否在任何时候说过它将停止另一个线程? -
文档说,如果尚未完成,则使用 CancellationException 完成此 CompletableFuture。
-
并且没有说“这将停止其他正在运行的线程”。
标签: java multithreading thread-safety threadpool