如何获得Completeablefuture的结果

时间:2016-06-09 13:33:27

标签: java future executorservice futuretask completable-future

在Main类中,我尝试使用CompletableFuture异步运行任务。并且如FMSMsgHandlerSupplier类的代码所示,它返回Double []

类型的数据

问题是,在Main类的for循环中,FMSMsgHandlerSupplier被调用5次,并假设对于每次迭代我都会收到数据类型的新值 Double [],如何在每次调用FMSMsgHandlerSupplier类后得到计算结果?

主要

public class Main {

private final static String TAG = Main.class.getSimpleName();

public static void main(String[] args) throws InterruptedException, ExecutionException {

    CompletableFuture<Double[]> compFuture = null;
    for (int i = 0; i < 5; i++) {
        compFuture = CompletableFuture.supplyAsync(new FMSMsgHandlerSupplier(1000 + (i*1000), "1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12"));
    }
}

}

FMSMsgHandlerSupplier

public class FMSMsgHandlerSupplier implements Supplier<Double[]>{

private final static String TAG = FMSMsgHandlerSupplier.class.getSimpleName();
private String mFMSMsg = ""; 
private static long sStartTime = TimeUtils.getTSMilli();
private int mSleepTime;

public FMSMsgHandlerSupplier(int sleepTime, String fmsMsg) {
    // TODO Auto-generated constructor stub
    this.mFMSMsg = fmsMsg;
    this.mSleepTime = sleepTime;
}

public Double[] get() {
    // TODO Auto-generated method stub
    if (this.mFMSMsg != null && !this.mFMSMsg.isEmpty()) {

        Double[] inputMeasurements = new Double[9];

        String[] fmsAsArray = this.toArray(this.mFMSMsg);
        inputMeasurements = this.getInputMeasurements(fmsAsArray);

        return inputMeasurements;

    } else {
        Log.e(TAG, "FMSMsgHandler", "fmsMsg is null or empty");

        return null;
    }
}

1 个答案:

答案 0 :(得分:1)

您可以使用completable future的get()方法来获取值。但这意味着你的循环会等到返回值。一个更好的契合将是thenAccept,thenRun ...等方法之一。例如,

public static void main(String[] args) {
    List<CompletableFuture> compFutures = new ArrayList<>();
    //timeout in seconds
    int TIMEOUT = 120; //or whatever
    for (int i = 0; i < 5; i++) {
    CompletableFuture<Double[]> compFuture = CompletableFuture.supplyAsync(new FMSMsgHandlerSupplier(1000 + (i*1000), "1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12"));
        compFuture.thenAcceptAsync(d -> doSomethingWithDouble(d));
        compFutures.add(compFuture);    
    }
    CompletableFuture.allOf(compFutures).get(TIMEOUT, TimeUnit.SECONDS);
}

public static void doSomethingWithDouble(Double[] d) {
    System.out.print(d);
}