2017-04-10 178 views
-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"; 
} 
} 
+1

什么是第47行? –

+0

你看过代码先生吗?它在那里System.out.println(“Line 47”); –

+0

这是否意味着这是第47行?或者是它下面的线47? –

回答

0

根据的Javadoc CompletableFuture#get

如有必要,等待这个未来完成,和n返回结果。

您需要将任务实际分配给每个CompletableFuture本身,否则它将无限期地挂起。