2016-10-04 5 views
0

私は別のスレッドでいくつかのメソッドを実行したいが、あるスレッドの結果を別のスレッドに渡したいという状況があります。クラスには以下のメソッドがあります。私は印刷結果に乗算する減算に加えて結果を渡すためにしようとしています複数のthenApply in completableFuture

public static void main(String[] args) { 
    int a = 10; 
    int b = 5; 
    CompletableFuture<String> cf = new CompletableFuture<>(); 
    cf.supplyAsync(() -> addition(a, b)) 
     .thenApply(r ->subtract(20,r) 
       .thenApply(r1 ->multiply(r1, 10)) 
       .thenApply(r2 ->convert(r2)) 
       .thenApply(finalResult ->{ 
        System.out.println(cf.complete(finalResult)); 
       })); 
    System.out.println(cf.complete("Done")); 

} 

:ここ

public static int addition(int a, int b){ 
    System.out.println((a+b)); 
    return (a+b); 
} 

public static int subtract(int a, int b){ 
    System.out.println((a-b)); 
    return (a-b); 
} 

public static int multiply(int a, int b){ 
    System.out.println((a*b)); 
    return (a*b); 
} 
public static String convert(Integer a){ 
    System.out.println((a)); 
    return a.toString(); 
} 

はmainメソッドです。しかし、コンパイルエラーが発生しています。ネストされたthenApply()を実行できないように見えます。私たちがこれを行う方法はありますか? google上でそれを検索し、有用なリンクを見つけました。http://kennethjorgensen.com/blog/2016/introduction-to-completablefuturesしかし、多くの助けは見つかりませんでした。

答えて

0

物事のカップルは、あなたのスニペットで間違っている:

  1. 括弧:あなたがいないsubstractメソッドの後、前1次のthenApply後の終了を開始する必要があります。
  2. supplyAsync()は静的メソッドです。それをそのまま使用してください。
  3. あなただけの最後の操作で結果を印刷したい場合は、代わりにthenApply
  4. thenAcceptを使用あなたはあなたが前にthenApplyでそれをしなければならないんでしょうどちらも(thenAcceptにCFを完了する必要はありません。

コードのこの作品は、コンパイルし、それはあなたが達成したいものに近いかもしれない:

CompletableFuture<Void> cf = CompletableFuture 
     .supplyAsync(() -> addition(a, b)) 
     .thenApply(r -> subtract(20, r)) 
     .thenApply(r1 -> multiply(r1, 10)) 
     .thenApply(r2 -> convert(r2)) 
     .thenAccept(finalResult -> { 
      System.out.println("this is the final result: " + finalResult); 
     }); 

    //just to wait until the cf is completed - do not use it on your program 
    cf.join(); 
+0

おかげでルーベンこれは動作しますこれは私が探していたまさにです。。。 – SarveshKaushal

関連する問題