1

在 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;
    }
}
4

1 回答 1

1

您可以使用可完成未来的 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);
}
于 2016-06-13T23:12:58.270 回答