【发布时间】:2023-11-11 11:47:01
【问题描述】:
我有检查 CompletableFuture 执行时间的方法。如果这样的 CompletableFuture 执行时间超过 2 秒,我想终止此任务。但是,如果我没有控制执行 CompletableFuture 方法的线程,我该怎么办?
final CompletableFuture<List<List<Student>>> responseFuture = new CompletableFuture<>();
responseFuture.supplyAsync(this::createAllRandomGroups)
.thenAccept(this::printGroups)
.exceptionally(throwable -> {
throwable.printStackTrace();
return null;
});
createAllRandomGroups()
private List<List<Student>> createAllRandomGroups() {
System.out.println("XD");
List<Student> allStudents = ClassGroupUtils.getActiveUsers();
Controller controller = Controller.getInstance();
List<List<Student>> groups = new ArrayList<>();
int groupSize = Integer.valueOf(controller.getGroupSizeComboBox().getSelectionModel().getSelectedItem());
int numberOfGroupsToGenerate = allStudents.size() / groupSize;
int studentWithoutGroup = allStudents.size() % groupSize;
if (studentWithoutGroup != 0) groups.add(this.getListOfStudentsWithoutGroup(allStudents, groupSize));
for(int i = 0; i < numberOfGroupsToGenerate; i++) {
boolean isGroupCreated = false;
while (!isGroupCreated){
Collections.shuffle(allStudents);
List<Student> newGroup = this.createNewRandomGroupOfStudents(allStudents, groupSize);
groups.add(newGroup);
if (!DataManager.isNewGroupDuplicated(newGroup.toString())) {
isGroupCreated = true;
allStudents.removeAll(newGroup);
}
}
}
DataManager.saveGroupsToCache(groups);
return groups;
}
printGroups()
private void printGroups(List<List<Student>> lists) {
System.out.println(lists);
}
此语句responseFuture.cancel(true); 不会杀死 responseFuture 正在执行方法的线程。那么终止 CompletableFuture 线程最优雅的方法是什么?
【问题讨论】:
-
你假设有一个线程要杀死。但这看起来就像一个异步操作链,可能根本没有线程在等待。你不想杀死一个线程,你想取消异步操作。
-
@DanielPryden 那么我怎样才能杀死这些操作呢?
-
这取决于什么操作需要花费时间。你能显示
createAllRandomGroups和printGroups的代码吗? -
@DanielPryden 当然,完成。
-
我是不是看错了什么?看起来您在这些方法中根本没有做任何异步工作。你为什么要使用 CompletableFuture?
标签: java multithreading java-8 future completable-future