目前,我需要执行异步任务以在completablefuture中进行同步。 例如。 任务A和任务B是不可替代的未来。 当任务A完成时,任务B运行。 这一次可以正常工作。 假设如果让它在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 getUserDetails(String name) {
return CompletableFuture.supplyAsync(() -> {
return UserService.getUser(name);
});
}
synchronized CompletableFuture getRating(User user) {
return CompletableFuture.supplyAsync(() -> {
return CreditRating.getCreditRating(user);
});
}
synchronized CompletableFuture getResult(Double rating) {
return CompletableFuture.supplyAsync(()-> {
return "welcome world";
});
}
public void main() throws InterruptedException, ExecutionException {
ThenCompose cc = new ThenCompose();
// then apply
CompletableFuture> result = cc.getUserDetails("kumaran").thenApply(user -> {
return cc.getRating(user);
});
// then compose
for (int i = 1; i <= 15; i++) {
CompletableFuture taskA = cc.getUserDetails("mike").thenCompose(user -> {
System.out.println("Task A --- " +Thread.currentThread().getName() + "--" + LocalTime.now());
return cc.getRating(user);
});
CompletableFuture 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。 请提出解决方案。