【发布时间】:2018-02-12 09:32:51
【问题描述】:
我想试验 CompletableFutures 的能力,为此我创建了简单的类 CompletableFutureTests
这是我的方法:
private static String name() {
System.out.println("Name");
return "ALmas";
}
@SneakyThrows(InterruptedException.class)
private static String surname(String name) {
Thread.sleep(2000);
System.out.println("sur");
return name+" Abdrazak";
}
private static String world(String name) {
System.out.println("world");
return name + " hello";
}
private void consumer(String str){
System.out.println("str");
}
private static String onExc(Exception name) {
return "on exception";
}
及用法
CompletableFuture.supplyAsync(CompletableFutureTests::name)
.thenApplyAsync(CompletableFutureTests::surname)
.thenApply(CompletableFutureTests::world)
.thenAccept(CompletableFutureTests::consumer);
这段代码把我扔了
RuntimeException: Uncompilable source code - Erroneous sym type: java.util.concurrent.CompletableFuture.thenAccept
由于这条线
.thenAccept(CompletableFutureTests::consumer)
当我用新类替换它时
private static class Test implements Consumer<String>{
@Override
public void accept(String t) {
System.out.println(t);
}
}
}
CompletableFuture.supplyAsync(CompletableFutureTests::name)
.thenApplyAsync(CompletableFutureTests::surname)
.thenApply(CompletableFutureTests::world)
.thenAccept(new Test());
它按方面工作。如您所见,对方法consumer 的方法引用和Test 类中的方法apply 是相同的
为什么第一个不起作用?
顺便说一句
为什么这个也是正确的
CompletableFuture.supplyAsync(CompletableFutureTests::name)
.thenApplyAsync(CompletableFutureTests::surname)
.thenApply(CompletableFutureTests::world)
.thenAccept(CompletableFutureTests::surname);
(我将方法引用传递给thenAccept,但thenAccept 应该将Consumer 作为参数)
【问题讨论】: