-1
我正在编写一个代码来探索Java8中的CompletableFuture,当我运行附加的代码时,它打印“第47行”并停止,它没有打印语句我在getRandomText()方法中,我不知道如果我失去了一些东西!Java8:CompletableFuture get()方法没有被触发/调用
* CompletableFutureTest *
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");
}
}
* FakeAPI1 *
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";
}
}
什么是第47行? –
你看过代码先生吗?它在那里System.out.println(“Line 47”); –
这是否意味着这是第47行?或者是它下面的线47? –