为什么这段代码在 Java 8 和 Java 11 中表现不同?
private static String test2() {
CompletableFuture
.runAsync(() -> IntStream.rangeClosed(1, 20).forEach(x -> {
try {
Thread.sleep(500);
System.out.println(x);
} catch (InterruptedException e) {
e.printStackTrace();
}
}));
return "Finish";
}
Run Code Online (Sandbox Code Playgroud)
我希望它打印完成,然后以 500 毫秒的间隔打印从 1 到 20 的数字,然后停止执行,它在 Java 8 中正常工作。
然而,当我在 Java 11 上运行完全相同的方法时,它打印 Finish 并终止,而没有调用 runAsync(...) 代码。我设法通过添加这样的 ExecutorService 来启动它
private static String test2() {
final ExecutorService executorService = Executors.newFixedThreadPool(10);
CompletableFuture
.runAsync(() -> IntStream.rangeClosed(1, 10).forEach(x -> {
try {
Thread.sleep(500);
System.out.println(x);
} catch (InterruptedException e) { …Run Code Online (Sandbox Code Playgroud) 我想触发许多一次性异步 CompletableFutures,如下所示:
for (Job job : jobs) {
CompletableFuture.supplyAsync(() -> job.process())
.whenComplete(this::doSomething);
}
Run Code Online (Sandbox Code Playgroud)
理想情况下,这些 CompletableFutures 可以在whenComplete完成后被垃圾回收。但是,由于我没有存储参考文献,因此是否存在事先收集它们的风险?
我试图运行以下类,使其终止而不执行CompletableFuture。
public class ThenApplyExample {
public static void main(String[] args) throws Exception {
//ExecutorService es = Executors.newCachedThreadPool();
CompletableFuture<Student> studentCompletableFuture = CompletableFuture.supplyAsync(() -> {
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
return 3;
})// If I put executorservice created n commented above, programme work as expected.
.thenApply(i -> {
for (int j = 0; j <= i; j++) {
System.out.println("Inside first then apply");
}
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("First then apply is …Run Code Online (Sandbox Code Playgroud) java multithreading java.util.concurrent concurrent.futures completable-future
我有以下代码(或多或少):
ExecutorService executor = Executors.newFixedThreadPool(10);
CompletableFuture
.supplyAsync(()->{
return longRunningMethodThatReturnsBoolean();
}, executor)
.thenAcceptAsync(taskResult -> {
logResult();
executor.shutdown();
}, executor);
Run Code Online (Sandbox Code Playgroud)
这允许主线程中的代码继续,但是我希望主线程在完成时死亡,并且未来继续在它自己的线程中工作,但是主线程保持活动状态直到 CompletableFuture 完成,即使主线程没有不再做任何事情。
我对这个有点陌生,我错过了什么吗?甚至有可能吗?
任何帮助将不胜感激!!!