JavaFX : Use a Thread more than once

前端 未结 3 2314
天命终不由人
天命终不由人 2021-02-20 14:38

I\'m new with JavaFX and I\'ve a little problem with a thread: I can execute it twice and I can\'t find why.

Here is a sum-upt of my code:

Task

        
3条回答
  •  别那么骄傲
    2021-02-20 15:23

    From the Thread.start() documentation : No

    It is never legal to start a thread more than once. In particular, a thread may not be restarted once it has completed execution.

    From the Concurrency in JavaFX tutorial :

    The Task class defines a one-time object that cannot be reused. If you need a reusable Worker object, use the Service class.

    So, you have to consider the Service class rather than Task.


    Edit: this should work for you:

    Service service = new Service<>(task);

    //Updated use this to create a new Service object instead
        Service service = new Service() {
        @Override
        protected Task createTask() {
            return new Task() {
                @Override
                protected Void call() throws Exception {
                    //Your codes here
                    return null;
                }
            };
        }
    };
    
    @FXML protected void launch(ActionEvent event){
         if (!service.isRunning()) {
            service.reset();
            service.start();
        }
    }
    

提交回复
热议问题