gpt4 book ai didi

java - 如何在 javafx 中操作 Future 的结果

转载 作者:行者123 更新时间:2023-12-01 22:25:09 24 4
gpt4 key购买 nike

这是我的 JavaFX Controller

public class MainController {
private Future<Graph> operation;
private ExecutorService executor = Executors.newSingleThreadExecutor();

@FXML
private void createSession() { //invoked by a button click in the view
//GraphCreationSession implements Callable<Graph>
GraphCreationSession graphSession = new GraphCreationSession();

if (operation != null && !operation.isDone()) {
//cancel previous session
operation.cancel(true);
}
operation = executor.submit(graphSession);
???
}
}

所以我的问题是,在 javaFX 上下文中处理 Future 结果的习惯用法是什么?

我知道我可以执行操作.get(),并且线程将阻塞直到操作完成,但我会阻塞应用程序线程。我正在考虑当 Callable 完成时进行回调,并且我发现了 CompletableFuture,这是通过 thenAccept 实现的。 但基于 this answer线程仍然会被阻塞,这违背了 Future 的要点,就像答案提到的那样。

在我的特定情况下,可调用的结果(我的示例中的图表)包含我希望在操作完成时在面板中显示的结果。

最佳答案

最简单的方法是更改​​ GraphCreationSession所以它是 Task<Graph> 的子类而不是 Callable<Graph> 的实现:

public class GraphCreationSession extends Task<Graph> {

@Override
public Graph call() throws Exception {
// implementation as before...
}
}

然后你就可以了

public class MainController {
private ExecutorService executor = Executors.newSingleThreadExecutor();
private GraphCreationSession graphSession ;

@FXML
private void createSession() { //invoked by a button click in the view

if (graphSession != null && !graphSession.getState()==Worker.State.RUNNING) {
//cancel previous session
graphSession.cancel(true);
}
graphSession = new GraphCreationSession();
graphSession.setOnSucceeded(event -> {
Graph graph = graphSession.getValue();
// update UI...
});
executor.execute(graphSession);
}
}

如果你无法改变GraphCreationSession ,或者希望它独立于 javafx API,然后将其包装在一个简单的 Task 中实现:

public class MainController {

private Task<Graph> graphSession ;
// ...

@FXML
public void createSession() {

// ...

graphSession = new Task<Graph>() {
@Override
public Graph call() throws Exception {
return new GraphCreationSession().call();
}
};

graphSession.setOnSucceeded(...);
executor.execute(graphSession);
}
}

关于java - 如何在 javafx 中操作 Future 的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28929563/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com