在关闭我的JavaFX程序之前停止线程 [英] Stop threads before close my JavaFX program

查看:214
本文介绍了在关闭我的JavaFX程序之前停止线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在关闭应用程序时遇到问题,因为在关闭应用程序后,某些线程仍在运行。
有人可以帮我一些方法来阻止所有线程在后台被执行然后杀死主线程???

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 Threads being executed in background before killing the main thread???

关于javafx的问题,我注意到许多新开发人员面临着管理Threads的问题。我想分享一下我为简化在javafx上管理线程的生活所做的工作。我已经创建了一个基于Android的AsyncTask的AsyncTask类,它基本上以简单但有效的方式执行Android的相同操作。您可以在 Github项目上找到有关它的更多信息

With my questions about javafx I have noticed that many newer developers are facing problem managing Threads. I would like to share what I have done to simplify my life about managing threads on javafx. I've created an AsyncTask class based on AsyncTask from Android that basically do the same of Android's in a humble but effective way. You can find more information about it on Github project

推荐答案

这里有三个选项 - 最简单的方法是简单地创建你的线程作为守护程序,这意味着当你的主程序结束时,所有守护线程也会终止。

You have three options here - the easiest is to simply create your Threads as deamons, which means that when your main program ends all deamon threads will terminate too.

Thread thread = new Thread();
thread.setDaemon(true);

这是最简单的,但缺点是你不会得到一个优雅的关闭(即线程会停止,你不会有机会进行资源管理等,这对你来说可能是也可能不是问题。)

Thats easiest, but the downside is that you wont get a graceful shutdown (ie the threads will stop, you wont get a chance to peform resource management etc, which may or may not be a problem for you).

另一种方法是保持产生的线程和当您的程序收到关闭信号时,您会迭代线程并传递某种信号以表示它们也应该终止

The alternative is to keep a hold on the spawned threads and when your program receives the signal to close you iterate over the threads and pass in a signal of some sort to signa that they too should terminate

volatile boolean shutdown = false;

public void shutdown() {
   shutdown = true;
}

public void run() {
    while(!shutdown) { 
        ... do your work here
    }
    ... perform any cleanup work here

(注意:为了清晰起见,忽略任何异常处理)

(Note: ignores any exception handling for clarity)

最后一个选项是在java.util.concurrent中使用Executor框架

The last option is to use the Executor framework in java.util.concurrent

ExecutorService executorService = Executors.newFixedThreadPool(10);
... assign/invoke tasks etc

... at some point later your program is told to shutdown 
... shutdown in executor too 
executorService.shutdown();
executorService.awaitTermination(10, TimeUnit.SECONDS); // wait for 10s in this case
executorService.shutdownNow();

这篇关于在关闭我的JavaFX程序之前停止线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆