首页 > 解决方案 > Java CompletableFuture - 主类未终止

问题描述

我正在尝试实现 CompletableFuture,它在完成时调用一个虚拟回调方法。

但是,在添加 CompletableFuture.get() 方法后,我的主类不会终止。我尝试用 Thread.sleep(5000) 替换 CompletableFuture.get() ,但这似乎不是正确的方法。请提出是什么导致 CompletableFuture.get() 即使线程完成也保持阻塞。

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.stream.IntStream;

public class CallableAsyncWithCallBack {

 public static void main(String[] args) throws InterruptedException {
  CompletableFuture<String> compFuture=new CompletableFuture<String>();
  compFuture.supplyAsync(()->{
   //Compute total
   long count=IntStream.range(Integer.MIN_VALUE, Integer.MAX_VALUE).count();
  return ""+count;
  }).thenApply(retVal->{ 
   try {
    return new CallBackAsynchClass(retVal).toString();
   } catch (InterruptedException | ExecutionException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
   return "";
  }
  );
 System.out.println("Main Thread 1");
 try {
  compFuture.get();
 } catch (ExecutionException e) {
  e.printStackTrace();
 }
 System.out.println("Lock cleared");
 }

}

class CallBackAsynchClass
{
 String returnVal="";
                 public CallBackAsynchClass(String ret) throws InterruptedException, ExecutionException {

                  System.out.println("Callback invoked:"+ret);
                  returnVal=ret;
                 }
                 @Override
                 public String toString() {
                  return "CallBackAsynchClass [returnVal=" + returnVal + "]";
                 }


}

我期待输出“锁定已清除”,但 .get() 似乎正在阻止锁定。

标签: java-8completable-future

解决方案


.thenApply函数返回一个新CompletableFuture的实例,你需要使用这个实例,尝试使用这种方式:

public class CallableAsyncWithCallBack {

    public static void main(String[] args) throws InterruptedException {
        CompletableFuture<String> compFuture = CompletableFuture.supplyAsync(() -> {
            //Compute total
            long count = IntStream.range(Integer.MIN_VALUE, Integer.MAX_VALUE).count();
            return "" + count;
        });

        CompletableFuture<String> future = compFuture.thenApply(retVal -> {
            try {
                return new CallBackAsynchClass(retVal).toString();
            } catch (InterruptedException | ExecutionException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return ""; });

        System.out.println("Main Thread 1");

        try {
            future.get();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        System.out.println("Lock cleared");
    }

}

希望这可以帮助


推荐阅读