2016-11-21 5 views
1

Ich schrieb ein einfaches Beispiel zu CompletableFuture zu verstehen. Aber wenn ich es auf der Konsole drucke. Es zeigen irgendwann nur „asyn Demo“ Dies ist mein CodeZeige falsche Daten mit Java 8 CompleableFuture

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())); 
    } 
} 

Antwort

2

Sie die asynchrone Operation starten, aber Sie warten nicht, bis es beendet - wenn Sie gedruckt haben asyn demo es gibt nichts anderes einen Nicht-Daemon-Thread am Leben zu halten, damit der Prozess beendet wird. Verwendung für die CompletableFuture<Void> von thenAccept zurück warten nur get() zu beenden:

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())); 
    } 
}