繁体   English   中英

如何立即关闭执行程序服务中的所有线程?

[英]How to shut down all threads in executor service immidiately?

我已经使用了shutDown()shutDownNow() ,但是这两种方法都不会立即停止所有线程。 在这两个中, shutDownNow()更可取,但是它等待正在运行的线程完成其任务。 在我的场景中,我有一个处理postgres数据库的巨大任务,我想立即关闭该线程,而不必等待执行完成。

立即关闭所有线程的方法是什么?

shutdownNow:尝试停止所有正在执行的任务,暂停正在等待的任务的处理,并返回正在等待执行的任务的列表。 此方法不等待主动执行的任务终止。 使用awaitTermination可以做到这一点。

shutdown:启动有序关闭,在该关闭中执行先前提交的任务,但不接受任何新任务。 如果已关闭,则调用不会产生任何其他影响。 此方法不等待先前提交的任务完成执行。 使用awaitTermination可以做到这一点。

http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ExecutorService.html#shutdown%28%29

或者您可以看到以下内容:

您可以改用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();

停止线程的唯一“干净”方法是,如果内部有一些循环,则通过一些布尔变量(例如“ stopThread”)停止循环,并且必须处理该变量。

例:

public void run(){

for(int i = 0; i <1000000 &&(!stopThread); i ++){

// do something

}}

我怀疑以安全的方式是否可行。

根据oracle 文档关闭执行程序服务的安全方法

 void shutdownAndAwaitTermination(ExecutorService pool) {
   pool.shutdown(); // Disable new tasks from being submitted
   try {
     // Wait a while for existing tasks to terminate
     if (!pool.awaitTermination(60, TimeUnit.SECONDS)) {
       pool.shutdownNow(); // Cancel currently executing tasks
       // Wait a while for tasks to respond to being cancelled
       if (!pool.awaitTermination(60, TimeUnit.SECONDS))
           System.err.println("Pool did not terminate");
     }
   } catch (InterruptedException ie) {
     // (Re-)Cancel if current thread also interrupted
     pool.shutdownNow();
     // Preserve interrupt status
     Thread.currentThread().interrupt();
   }
 }

如果您真的想遵循粗略的方法,我将建议一个可能不是100%准确的解决方案,并且我个人不建议这样做。 我想使用ExecutorService方法而不是此粗略的解决方案。

  1. 创建自己的线程和线程池按本文章
  2. Worker线程中再添加一个布尔boolean runNow = true;
  3. Worker线程的run方法将如下所示: while ( runNow) { // your logic }
  4. 当您要关闭所有线程时,请在ThreadPoolManager添加一个方法。 遍历myQueue并中断所有Runnables 捕获中断的异常并将布尔型runNow为false。

根据您调用数据库的方式,您可以尝试显式取消查询。 相关问题

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM