2016-11-21 19 views
1

我寫了一個簡單的例子來理解CompletableFuture。但是,當我在控制檯上打印它。有時它只是顯示「ASYN演示」 這是我的代碼使用java顯示錯誤的數據8 CompletableFuture

public class DemoAsyn extends Thread { 
    public static void main(String[] args) { 
     List<String> mailer = Arrays.asList("[email protected]", "[email protected]", "[email protected]", "[email protected]", 
       "[email protected]"); 

     Supplier<List<String>> supplierMail =() -> mailer; 
     Consumer<List<String>> consumerMail = Mail::notifyMessage; 
     Function<List<String>,List<String>> funcMail = Mail::sendMessage; 
     CompletableFuture.supplyAsync(supplierMail).thenApply(funcMail).thenAccept(consumerMail); 
     System.out.println("asyn demo"); 
    } 
} 


public class Mail { 

    public static List<String> sendMessage(List<String> notifies) { 
     notifies.forEach(x -> System.out.println("sent to " + x.toString())); 
     return notifies; 
    } 

    public static void notifyMessage(List<String> notifies) { 
     notifies.forEach(x -> System.out.println("notified to " + x.toString())); 
    } 
} 

回答

2

開始異步操作,但你不等待它完成 - 當你打印asyn demo沒有什麼別的保持一個非守護線程活着,所以這個過程終止。只需等待由thenAccept返回CompletableFuture<Void>完成使用get()

import java.util.*; 
import java.util.concurrent.*; 
import java.util.function.*; 

public class Test { 
    public static void main(String[] args) 
     throws InterruptedException, ExecutionException { 
     List<String> mailer = Arrays.asList(
       "[email protected]", 
       "[email protected]", 
       "[email protected]", 
       "[email protected]", 
       "[email protected]"); 

     Supplier<List<String>> supplierMail =() -> mailer; 
     Consumer<List<String>> consumerMail = Test::notifyMessage; 
     Function<List<String>,List<String>> funcMail = Test::sendMessage; 
     CompletableFuture<Void> future = CompletableFuture 
      .supplyAsync(supplierMail) 
      .thenApply(funcMail) 
      .thenAccept(consumerMail); 
     System.out.println("async demo"); 
     future.get(); 
    } 


    private static List<String> sendMessage(List<String> notifies) { 
     notifies.forEach(x -> System.out.println("sent to " + x.toString())); 
     return notifies; 
    } 

    private static void notifyMessage(List<String> notifies) { 
     notifies.forEach(x -> System.out.println("notified to " + x.toString())); 
    } 
}