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

时间:2016-02-24 18:22:58

标签: java multithreading javafx

当事件从具有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");
        }
       }
      }
     }
    }

1 个答案:

答案 0 :(得分:1)

致电Platform.runLater(this::redraw);