在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;
}
}
最佳答案
您可以使用completable future的get()方法获取值。但这意味着您的循环将等到返回值。更好的适合方法是thenAccept,thenRun ... etc方法。例如,
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);
}
关于java - 如何获得Completablefuture的结果,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37727492/