gpt4 book ai didi

java - 如何从用作 WatchService 的线程调用主线程中的方法?

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

当事件从具有 WatchService 的不同线程触发时,需要调用主类中定义的 redraw() 方法。如何让它发挥作用?

    public class Main extends Application {

@Override
public void start(Stage primaryStage) throws Exception {
List < String > args = getParameters().getRaw();

Runnable watchFileChangesThread = () -> {
try {
setUpWatchService();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
};
new Thread(watchFileChangesThread).start();
//...
}
private void redraw(){//redraw UI}
private void setUpWatchService() throws IOException, InterruptedException {
final Path path = FileSystems.getDefault().getPath(System.getProperty("user.dir"), "");
System.out.println(path);
try (final WatchService watchService = FileSystems.getDefault().newWatchService()) {
final WatchKey watchKey = path.register(watchService, StandardWatchEventKinds.ENTRY_MODIFY);
while (true) {
final WatchKey wk = watchService.take();
for (WatchEvent < ? > event : wk.pollEvents()) {
final Path changed = (Path) event.context();
System.out.println(changed);
if (changed.endsWith("input.txt")) {
System.out.println("My file has changed");
}
}
// reset the key
boolean valid = wk.reset();
if (!valid) {
System.out.println("Key has been unregistered");
}
}
}
}
}

最佳答案

调用Platform.runLater(this::redraw);

关于java - 如何从用作 WatchService 的线程调用主线程中的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35610038/

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