我知道来自get()的CompletableFuture方法阻塞线程,但是在Future处理过程中如何实现执行System.out.println("xD"),因为现在这个语句是在CompletableFuture完成时执行的。
import java.util.concurrent.*;
import java.util.stream.Stream;
public class CompletableFutureTest {
public static void main(String[] args) throws ExecutionException, InterruptedException {
CompletableFuture.supplyAsync(CompletableFutureTest::counting).whenComplete((result, exception) -> {
if (exception != null) {
System.out.println(result);
} else {
}
}).get();
System.out.println("xD");
}
public static int counting() {
Stream.iterate(1, integer -> integer +1).limit(5).forEach(System.out::println);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return 10;
}
}发布于 2017-11-29 13:51:04
您应该在print语句之后移动get()。
这样,在计算来自future的值时,将执行打印。
public static void main(String[] args) throws ExecutionException, InterruptedException {
CompletableFuture<Integer> future = CompletableFuture.supplyAsync(CompletableFutureTest::counting).whenComplete((result, exception) -> {
if (exception != null) {
System.out.println(result);
} else {
}
});
System.out.println("xD");
Integer value = future.get();
}https://stackoverflow.com/questions/47554231
复制相似问题