Stop threads before close my JavaFX program

后端 未结 5 1145
迷失自我
迷失自我 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 17:38

    Executors from the java.util.concurrent package are the way to go. Explicitly:

    ExecutorService executorService = Executors.newCachedThreadPool(new ThreadFactory() {
         @Override
         public Thread newThread(Runnable runnable) {
              Thread thread = Executors.defaultThreadFactory().newThread(runnable);
              thread.setDaemon(true);
              return thread;
        }
    });
    

    Java 8 version with fixed ScheduledExecutorService

    ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1, r -> {
        Thread thread = Executors.defaultThreadFactory().newThread(r);
        thread.setDaemon(true);
        return thread;
    });
    

提交回复
热议问题