java8 completablefuture在for循环中,强制async同步或类似于链



目前我有一个要求,让异步任务在可完成的将来同步。任务A和任务B是可以完成的。任务B在任务A完成时运行。这适用于单次。假设我让它在foor循环中运行,显然它会创建n个异步调用来实现结果。正因为如此,我在下面得到了类似的o/p

A
B
A
A
B
B
A
B
A
A
A

我想实现像

A
B
A
B
A
B
A
B

这是代码,

package com.demo.completable.combine;
import javax.xml.stream.Location;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;
public class ThenCompose {
synchronized CompletableFuture<User> getUserDetails(String name) {
return CompletableFuture.supplyAsync(() -> {
return UserService.getUser(name);
});
}
synchronized CompletableFuture<Double> getRating(User user) {
return CompletableFuture.supplyAsync(() -> {
return CreditRating.getCreditRating(user);
});
}
synchronized CompletableFuture<String> getResult(Double rating) {
return CompletableFuture.supplyAsync(()-> {
return "welcome world";
});
}
public void main() throws InterruptedException, ExecutionException {
ThenCompose cc = new ThenCompose();
// then apply
CompletableFuture<CompletableFuture<Double>> result = cc.getUserDetails("kumaran").thenApply(user -> {
return cc.getRating(user);
});
// then compose
for (int i = 1; i <= 15; i++) {
CompletableFuture<Double> taskA = cc.getUserDetails("mike").thenCompose(user -> {
System.out.println("Task A --- " +Thread.currentThread().getName() + "--" + LocalTime.now());
return cc.getRating(user);
});
CompletableFuture<String> fileLocation =
taskA.thenCompose(ts -> {
System.out.println("Task B --- " +Thread.currentThread().getName() + "--- " + LocalTime.now());
return getResult(ts);

});
}
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
ThenCompose tc = new ThenCompose();
tc.main();
}
}

加入join和get会起作用,但我不应该同时使用join和get。请提出解决方案。

请尝试以下按顺序执行任务的代码。它会给你预期的结果。

static Integer methA(int seq) {
System.out.println("A-"+seq);
return seq;
}
static Integer methB(int seq) {
System.out.println("B-"+seq);
return seq;
}
public static void main(String[] args) throws InterruptedException, ExecutionException {
System.out.println("Main started:");
CompletableFuture<Integer> ft = null;
for(int a=0;a<15;a++) {
final int seq = a;
if(ft==null) {
ft = CompletableFuture.supplyAsync(()->methA(seq))
.thenApply(s->methB(s));
}else {
ft.thenApply((s)->methA(seq))
.thenApply(s->methB(s));
}
}
ft.thenAccept(s->System.out.println("Thread completed..."+s));
System.out.println("Main ended:");
}

最新更新