Java8:CompletableFuture get()方法未被激发/调用
我正在用Java8编写一个代码来探索CompletableFuture,当我运行附加的代码时,它打印“第47行”并停止,它没有打印我在getRandomText()方法中的语句,我不确定我是否遗漏了什么 *CompletableFutureTest*Java8:CompletableFuture get()方法未被激发/调用,java,Java,我正在用Java8编写一个代码来探索CompletableFuture,当我运行附加的代码时,它打印“第47行”并停止,它没有打印我在getRandomText()方法中的语句,我不确定我是否遗漏了什么 *CompletableFutureTest* public class CompletableFutureTest { public static void main(String[] args) throws InterruptedException,ExecutionE
public class CompletableFutureTest {
public static void main(String[] args)
throws InterruptedException,ExecutionException {
List<CompletableFuture<FakeAPI1>> apis=
Arrays.asList(
new CompletableFuture<FakeAPI1>(),
new CompletableFuture<FakeAPI1>(),
new CompletableFuture<FakeAPI1>()
);
Long start= System.currentTimeMillis();
CompletableFuture<String> stringFuture=new CompletableFuture<String>();
System.out.println("Line 42");
List<String> list=apis.stream()
.map(api->
{
try{
System.out.println("Line 47");
String value =api.get().getRandomText();
System.out.println("Line 49");
stringFuture.complete(value);
System.out.println("Line 51");
return value;
}catch(ExecutionException e){
System.out.println("ExecutionException");
}catch(InterruptedException e){
System.out.println("InterruptedException");
}
return "NA";
})
.collect(Collectors.toList());
System.out.println("Line 55");
list.stream().forEach(System.out::println);
Long end= System.currentTimeMillis();
System.out.println("CompletableFutureTest took " + (end-start) + " ms" );
}
}
public class FakeAPI1 implements FakeAPI{
@Override
public void consume(){
try{
Thread.sleep(1000L);
System.out.println("Hello from FakeAPI1");
}catch(InterruptedException e){
System.out.println("Eat it silently");
}
}
public String getRandomText(){
System.out.println("getRandomText() @ FakeAPI1 was called ");
try{
Thread.sleep(1000L);
return "Hello from FakeAPI1";
}catch(InterruptedException e){
System.out.println("Eat it silently");
}
return "Default message from FakeAPI1";
}
}
根据Javadoc for
CompletableFuture#get
:
如有必要,等待此未来完成,然后返回其结果
您需要实际为每个
CompletableFuture
本身分配一个任务,否则它将无限期挂起。第47行是什么?您看过代码了吗,先生?它就在那里System.out.println(“第47行”);那是不是说那是第47行?还是它下面的行是47?我更新了问题,它打印了“行47”和stopsm我猜它抛出了一个你决定不在catch块中处理的异常。