如何停止Java程序的线程? [英] How to stop threads of a Java program?

查看:128
本文介绍了如何停止Java程序的线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用GUI创建了一个java程序,并在其上放置了一个停止按钮。当我启动程序时,主线程启动10个线程。现在我希望每当用户点击停止按钮时,所有线程应首先终止,然后主线程应该终止。我怎么能这样做。

I have made a java program with GUI and have placed a "stop" button on it. When I start the program, the main thread starts 10 threads. Now I want that whenever a user click on "stop" button, all the threads should terminate first, then the main thread should terminate. How can I do that.

推荐答案

这取决于你想要10个线程终止的方式,以及你如何运行线程。

It depends on how you want to the 10 threads to "terminate", and how you are running the threads.

我建议创建 ExecutorService ,并将线程写为 Runnable 实施。这些 Runnable 对象应该响应对 interrupt() 通过中止任务,清理和退出<$来执行其执行的线程c $ c>尽快运行方法。

I recommend creating an ExecutorService, and writing your "threads" as Runnable implementations. These Runnable objects should respond to calls to interrupt() on their thread of execution by aborting their task, cleaning up, and exiting the run method as quickly as possible.

提交这些 Runnable 任务 ExecutorService 然后调用 awaitTermination ,全部在主线程中。当用户按下停止按钮时,调用 关闭 shutdownNow ExecutorService (来自事件派发线程)。

Submit these Runnable tasks to an ExecutorService then call awaitTermination, all in the main thread. When the user presses the "stop" button, call shutdown or shutdownNow as desired on the ExecutorService (from the event dispatch thread).

如果在执行程序服务上调用 shutdownNow ,它将通知通过中断线程来运行任务。如果您调用 shutdown ,它将允许任务完成而不会中断。无论如何,您的主线程将阻止 awaitTermination ,直到所有任务都完成(或时间限制用完)。

If you call shutdownNow on the executor service, it will notify the running tasks by interrupting their threads. If you call shutdown, it will allow the tasks to complete without interruption. Regardless, your main thread will block on awaitTermination until all of the tasks have completed (or the time limit runs out).

当然,您可以使用 join 自行创建和管理所有线程。关键是如果你想要能够过早地阻止线程,可以使线程中断。

You can, of course, create and manage of all of the threads yourself, using join. The key is to make the threads interruptible if you want to be able to stop them prematurely.

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

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