如何关闭在我的 Java 应用程序中运行的所有线程?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13154680/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to close all Threads running in my java application?
提问by milind_db
I want to close all thread which I started previously.
我想关闭我之前开始的所有线程。
Thread.currentThread()gives me current thread, but what about others? How can I get them?
Thread.currentThread()给我当前线程,但其他线程呢?我怎样才能得到它们?
I think Thread.activeCount()returns the count of active threads in thread's thread group, but I does not use ThreadGroup, I just started threads using Thread thread = new Thread(new MyRunnable()).
我认为Thread.activeCount()返回线程线程组中活动线程的计数,但我没有使用ThreadGroup,我只是使用Thread thread = new Thread(new MyRunnable())启动了线程。
So how can I achieve this? thanks in advance...
那么我怎样才能做到这一点呢?提前致谢...
回答by Peter Lawrey
You can use an ExecutorService instead which combines a thread pool with a queue of tasks.
您可以使用 ExecutorService 代替,它将线程池与任务队列相结合。
ExecutorService service = Executors.newCachedThreadPool();
// or
ExecutorService service = Executors.newFixedThreadPool(THREADS);
// submit as many tasks as you want.
// tasks must honour interrupts to be stopped externally.
Future future = service.submit(new MyRunnable());
// to cancel an individual task
future.cancel(true);
// when finished shutdown
service.shutdown();
回答by Tudor
You can simply keep references to all the threads somewhere (like a list) and then use the references later.
您可以简单地将所有线程的引用保留在某处(如列表),然后稍后使用这些引用。
List<Thread> appThreads = new ArrayList<Thread>();
Every time you start a thread:
每次启动线程时:
Thread thread = new Thread(new MyRunnable());
appThreads.add(thread);
Then when you want to signal termination (not via stop
I hope :D) you have easy access to the threads you created.
然后,当您想要发出终止信号(不是通过stop
我希望 :D)时,您可以轻松访问您创建的线程。
You can alternatively use an ExecutorService
and call shutdown when you no longer need it:
ExecutorService
当您不再需要它时,您也可以使用and call shutdown :
ExecutorService exec = Executors.newFixedThreadPool(10);
...
exec.submit(new MyRunnable());
...
exec.shutdown();
This is better because you shouldn't really create a new thread for each task you want to execute, unless it's long running I/O or something similar.
这更好,因为您不应该为要执行的每个任务真正创建一个新线程,除非它是长时间运行的 I/O 或类似的东西。
回答by IllegalArgumentException
If you wish to keep using the Thread object directly and not using ready-to-use thread services from java.util.concurrentyou should keep a references to all started thread (for example, put them in a List) and when wish to to close them, or interrupt them to stop, loop over the List.
如果您希望继续直接使用 Thread 对象而不使用来自java.util.concurrent 的现成线程服务,您应该保留对所有已启动线程的引用(例如,将它们放入列表中)以及何时需要关闭它们,或中断它们停止,循环遍历列表。