JavaFX 耗时操作安排

import javafx.application.Application;
import javafx.application.Platform;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.ListView;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;

public class JavaFXThreadTest extends Application {

    @Override
    public void start(Stage primaryStage) {
        Pane pane = new Pane();
        pane.setPrefWidth(200);
        pane.setPrefHeight(400);

        // 顺序加载多个子控件,ListView的性能远强于VBox
        ListView listView = new ListView();

        /*Task task = new Task() {
            @Override
            protected ListView call() {
                // 非FX线程
                // 建议进行耗时操作
                long start = System.currentTimeMillis();
                for (int i = 0; i < 100000; i++) {
                    listView.getItems().add(new Label("item" + i));
                    System.out.println("item" + i);
                }

                System.out.println("call-isInFxApplicationThread:" + Platform.isFxApplicationThread());
                System.out.println("call-time:" + (System.currentTimeMillis() - start));
                return listView;
            }

            @Override
            protected void updateValue(ListView listView) {
                // FX线程
                // 建议进行省时操作
                super.updateValue(listView);
                System.out.println("updateValue-isInFxApplicationThread:" + Platform.isFxApplicationThread());
                long start = System.currentTimeMillis();
                pane.getChildren().add(listView);
                System.out.println("updateValue-time:" + (System.currentTimeMillis() - start));
            }
        };
        new Thread(task).start();*/

        new Thread(() -> {
            // 非FX线程
            // 建议进行耗时操作
            long start1 = System.currentTimeMillis();
            for (int i = 0; i < 100000; i++) {
                listView.getItems().addAll(new Label("item" + i));
                System.out.println("item" + i);
            }

            System.out.println("init-isInFxApplicationThread:" + Platform.isFxApplicationThread());
            System.out.println("init-time:" + (System.currentTimeMillis() - start1));

            Platform.runLater(() -> {
                // FX线程
                // 建议进行省时操作
                long start2 = System.currentTimeMillis();
                pane.getChildren().add(listView);
                System.out.println("add-time:" + (System.currentTimeMillis() - start2));
                System.out.println("add-isInFxApplicationThread:" + Platform.isFxApplicationThread());
            });
        }).start();

        primaryStage.setTitle("JavaFXThreadTest");
        Scene scene = new Scene(pane);
        primaryStage.setScene(scene);
        primaryStage.show();
    }


    public static void main(String[] args) {
        launch(args);
    }
}

 

你可能感兴趣的:(#,JavaFX)