2016-11-21 4 views
1

私はCompletableFutureを理解するための簡単な例を書いています。しかし、私はそれをコンソールに印刷します。あなたが印刷されてきたときasyn demo他には何もありません - いつかそれだけ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デモ」と表示しますデーモン以外のスレッドを生きたままにしておくと、プロセスは終了します。 CompletableFuture<Void>thenAcceptによって返されるのを待ってから、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())); 
    } 
} 
関連する問題