简体   繁体   English

中断执行程序线程池中的可运行对象

[英]Interrupting a runnable in executor threadpool

Suppose I started 10 threads using executor framework in java. 假设我在Java中使用executor框架启动了10个线程。 I want to stop/interrupt a callables based on certain conditions later on. 我想稍后根据某些条件停止/中断可调用对象。 What is the best way to do that. 这样做的最好方法是什么。 I understand future.cancel(true), does not solve the issue. 我了解future.cancel(true),无法解决问题。

Check this article. 检查本文。

Calling shutdownNow() or cancel() doesn't stop the ongoing runnable. 调用shutdownNow()或cancel()不会停止正在进行的可运行对象。 What these methods do is simply call .interrupt() on the respective thread(s). 这些方法所做的只是在相应线程上调用.interrupt()。 The problem is, your runnable doesn't handle InterruptedException (and it can't). 问题是,您的runnable不处理InterruptedException(并且不能)。 It's a pretty common problem described in multiple books and articles, but still it's a bit counterintuitive. 这是在许多书籍和文章中描述的一个非常普遍的问题,但是仍然有点违反直觉。

In order to do that, you need to do quite a few things. 为此,您需要做很多事情。

  • Extend Runnable 扩展可运行
  • Make the “cancellable” resources (eg the input stream) an instance field, which provide a cancel method to your extended runnable, where you get the “cancellable” resource and cancel it (eg call inputStream.close()) 将“可取消”资源(例如输入流)设置为实例字段,该实例字段为您的扩展可运行对象提供取消方法,在此您可以获取“可取消”资源并将其取消(例如调用inputStream.close())
  • Implement a custom ThreadFactory that in turn creates custom Thread instances that override the interrupt() method and invoke the cancel() method on your extended Runnable 实现一个自定义ThreadFactory,依次创建覆盖interrupt()方法的自定义Thread实例,并在扩展的Runnable上调用cancel()方法
  • Instantiate the executor with the custom thread factory (static factory methods take it as an argument) 使用自定义线程工厂实例化执行程序(静态工厂方法将其作为参数)
  • Handle abrupt closing/stopping/disconnecting of your blocking resources, in the run()method 在run()方法中处理突然关闭/停止/断开您的阻塞资源

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

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