gpt4 book ai didi

multithreading - Javafx从线程Java 8更新UI

转载 作者:行者123 更新时间:2023-12-03 13:17:01 25 4
gpt4 key购买 nike

我对一项有趣的任务感兴趣。我在JavaFx中拥有UI,并带有另一个更新UI的线程。我从Platform.runLater开始更新。代码:

private void startUpdateDaemon() {
updateUserStatus();
updateTable();
}

private void startUpdateDaemonTask() {
Task task = new Task<Void>() {
@Override
protected Void call() throws Exception {
while (true) {
Platform.runLater(() -> {
startUpdateDaemon();
});
Thread.sleep(1000);
}
}
};
Thread th = new Thread(task);
th.setDaemon(true);
th.start();
}

@Override
public void initialize(URL location, ResourceBundle resources) {
startUpdateDaemonTask();
}

另外,我在另一个类中还可以更新UI:
private void startUpdateDaemonTask() {
Task task = new Task<Void>() {
@Override
protected Void call() throws Exception {
while (true) {
Platform.runLater(new Runnable() {
@Override
public void run() {
updateGameStatus();
}
});
Thread.sleep(1000);
}
}
};

Thread th = new Thread(task);
th.setDaemon(true);
th.start();
}

因此,最后我在两个地方调用了“Platform.runLater”,并在其中放置了不同的方法。
我的问题是我可以一次调用“Platform.runLater”创建仅一个“方法”,然后将要调用的不同方法发送给该方法吗?可能我可以与使用者编写finish方法,并向他发送方法“startUpdateDaemon()”和“updateGameStatus()”吗?
非常感谢。

最佳答案

您可以在方法中添加Runnable参数。这个参数给你Platform.runLater:

private void startUpdateDaemonTask(Runnable runner) {
Task task = new Task<Void>() {
@Override
protected Void call() throws Exception {
while (true) {
Platform.runLater(runner);
Thread.sleep(1000);
}
}
};

Thread th = new Thread(task);
th.setDaemon(true);
th.start();
}

现在,您可以使用方法引用来调用此方法:
startUpdateDaemonTask(this::startUpdateDaemon);
startUpdateDaemonTask(this::updateGameStatus);

关于multithreading - Javafx从线程Java 8更新UI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44239194/

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