JavaFX working with threads and GUI

前端 未结 2 692
予麋鹿
予麋鹿 2020-12-02 21:58

I have a problem while working with JavaFX and Threads. Basically I have two options: working with Tasks or Platform.runLater. As I understand

2条回答
  •  长情又很酷
    2020-12-02 22:25

    As puce says, you have to use Task or Service for the things that you need to do in background. And Platform.runLater to do things in the JavaFX Application thread from the background thread.

    You have to synchronize them, and one of the ways to do that is using the class CountDownLatch.

    Here is an example:

    Service service = new Service() {
            @Override
            protected Task createTask() {
                return new Task() {           
                    @Override
                    protected Void call() throws Exception {
                        //Background work                       
                        final CountDownLatch latch = new CountDownLatch(1);
                        Platform.runLater(new Runnable() {                          
                            @Override
                            public void run() {
                                try{
                                    //FX Stuff done here
                                }finally{
                                    latch.countDown();
                                }
                            }
                        });
                        latch.await();                      
                        //Keep with the background work
                        return null;
                    }
                };
            }
        };
        service.start();
    

提交回复
热议问题