如何关闭java应用程序中运行的所有线程?
我想关闭之前启动的所有线程 Thread.currentThread()为我提供当前线程,但其他线程呢?我怎样才能得到它们 我认为Thread.activeCount()返回线程的线程组中活动线程的计数,但我不使用ThreadGroup, 我刚开始使用Thread-Thread=new-Thread(new-MyRunnable())执行线程 那么我如何才能做到这一点呢?如何关闭java应用程序中运行的所有线程?,java,multithreading,threadpool,runnable,Java,Multithreading,Threadpool,Runnable,我想关闭之前启动的所有线程 Thread.currentThread()为我提供当前线程,但其他线程呢?我怎样才能得到它们 我认为Thread.activeCount()返回线程的线程组中活动线程的计数,但我不使用ThreadGroup, 我刚开始使用Thread-Thread=new-Thread(new-MyRunnable())执行线程 那么我如何才能做到这一点呢? 提前感谢…您可以使用ExecutorService,它将线程池与任务队列相结合 ExecutorService servic
提前感谢…您可以使用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();
您可以使用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();
您可以简单地将对所有线程的引用保留在某个位置(如列表),然后稍后使用这些引用
List<Thread> appThreads = new ArrayList<Thread>();
然后,当您想要发出终止信号时(不是通过stop
I hope:D),您可以轻松访问您创建的线程
您也可以使用ExecutorService
并在不再需要时调用shutdown:
ExecutorService exec = Executors.newFixedThreadPool(10);
...
exec.submit(new MyRunnable());
...
exec.shutdown();
这更好,因为您不应该为每个要执行的任务创建新线程,除非它是长时间运行的I/O或类似的任务。您只需将对所有线程的引用保留在某个位置(如列表),然后稍后使用引用即可
List<Thread> appThreads = new ArrayList<Thread>();
然后,当您想要发出终止信号时(不是通过stop
I hope:D),您可以轻松访问您创建的线程
您也可以使用ExecutorService
并在不再需要时调用shutdown:
ExecutorService exec = Executors.newFixedThreadPool(10);
...
exec.submit(new MyRunnable());
...
exec.shutdown();
这更好,因为您不应该为要执行的每个任务创建新线程,除非它是长时间运行的I/O或类似的任务。如果您希望继续直接使用thread对象,而不使用来自的ready to use thread services,您应该保留对所有已启动线程的引用(例如,将它们放在列表中)如果您希望直接使用Thread对象而不使用ready to use Thread服务,则应保留对所有已启动线程的引用(例如,将它们放入列表中),如果您希望关闭它们或中断它们以停止,则应保留对所有已启动线程的引用,循环浏览列表。我想在随机时间内分别运行这些线程,然后中断或停止它们。我认为service.shutdown()会在所有线程执行完成后停止它们,对吗?ExecutorService有一个执行任务的线程池。提交的任务将在停止线程之前执行。在文档中:“启动有序关机,其中执行以前提交的任务,但不接受新任务”。我添加了一个如何取消和中断单个任务的示例。您可以使用
service.shutdownNow()代码>在处理过程中杀死线程。我想随机运行这些线程,然后中断或停止它们。我认为service.shutdown()会在所有线程执行完成后停止它们,对吗?ExecutorService有一个执行任务的线程池。提交的任务将在停止线程之前执行。在文档中:“启动有序关机,其中执行以前提交的任务,但不接受新任务”。我添加了一个如何取消和中断单个任务的示例。您可以使用service.shutdownNow()代码>以在处理时终止线程。