Understanding the JavaFX WebView Streaming Model

I am trying to understand how JavaFX threads work. The descriptions here do not help.

For example, in the following order, the print order is always A, then B, then Z, which assumes that both the call load()and the code inside changed()work in the same thread.

But I don’t understand why the thread will not just exit after the last one Thread.sleep(2000)(since it won’t work anymore)?

I would expect that the code inside changed()will run in a new thread every time, and I absolutely do not understand how this works!

public class Test extends Application {

  @Override
  public void start(Stage stage) throws Exception {

    final WebView webView = new WebView();
    Scene scene = new Scene(webView);
    stage.setScene(scene);
    stage.show();

    webView.getEngine().getLoadWorker().stateProperty()
        .addListener(new ChangeListener<State>() {
      @Override
      public void changed(ObservableValue<? extends State> ov, State t, State t1) {
        if (t1 == Worker.State.SUCCEEDED) {
          System.out.println("Z"); // <---
        }
      }
    });

    webView.getEngine().load("http://www.google.com");

    System.out.println("A"); // <---
    Thread.sleep(2000);
    System.out.println("B"); // <---
    Thread.sleep(2000);
  }

  public static void main(String[] args) {
    launch(args);
  }
}
+4
source share
1 answer

Short answer

start() changed() "JavaFX Application Thread". , . Runnable.run(), , start() "JavaFX Application Thread" - : start() , . ( / , , .)

.

( ):

    public void start(Stage stage) throws Exception {
System.out.println("2: " + Thread.currentThread().getName());
        ...
        webView.getEngine().getLoadWorker().stateProperty().addListener(new ChangeListener<State>() {
                    @Override
                    public void changed(ObservableValue<? extends State> ov, State t, State t1) {
                        if (t1 == Worker.State.SUCCEEDED) {
System.out.println("3: " + Thread.currentThread().getName());
                            System.out.println("Z"); // <---
                        }
                    }
                });

        webView.getEngine().load("...");

        System.out.println("A"); // <---
        Thread.sleep(2000);
        System.out.println("B"); // <---
        Thread.sleep(2000);
    }

    public static void main(String[] args) {
System.out.println("1: " + Thread.currentThread().getName());
        launch(args);
System.out.println("4: " + Thread.currentThread().getName());
    }

:

:
: :

1: main
2: JavaFX Application Thread

: ... ! ? "Thread Application" JavaFX, , sleep() -ing, "A".

: "" 2
: "B", -

: "B" 2
: , ; sleep(), .

, , , start() , launch() , , . :

:

3: JavaFX Application Thread
Z

:
:

4: main

: ,

, main() start() .

: sleep() - , , , .

+3

All Articles