Stop threads before close my JavaFX program

后端 未结 5 1154
迷失自我
迷失自我 2020-12-14 17:05

I\'m having a problem with closing my application because some threads are still running after I close the application. Somebody can help me with some method to stop all Th

5条回答
  •  不知归路
    2020-12-14 18:03

    The method Platform.exit() belongs to the JavaFX context. When you call Platform.exit(), the method javafx.application.Application#stop() is called before the context terminates. Put inside the stop() method everything that needs to be executed before the JavaFX context terminates.

    With the System.exit(0) method, the application terminate abruptly. This method is not secure because if at the moment you call System.exit(0) and a Job is still running, maybe executing a write in the database, the application will not wait the Job fihish resulting in a corrupted database.

    I have an application running JavaFX with SpringBoot and a thread pool. That is how I handle it.

    //...
    import javafx.application.Application;
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.context.ConfigurableApplicationContext;
    
    import java.util.concurrent.Executors;
    import java.util.concurrent.ScheduledExecutorService;
    
    @SpringBootApplication
    public class Main extends Application {
    
        ConfigurableApplicationContext context;
    
        ScheduledExecutorService scheduledExecutorService;
    
    
        @Override
        public void init() {
    
            this.context = SpringApplication.run(getClass());
    
            this.context.getAutowireCapableBeanFactory().autowireBean(this);
    
            this.scheduledExecutorService = Executors.newScheduledThreadPool(10);
    
        }
    
        @Override
        public void stop() throws Exception {
    
            super.stop();
    
            this.context.close();
    
            this.scheduledExecutorService.shutdownNow();
    
        }
    
    
        // ...
    
    }
    

提交回复
热议问题