【发布时间】:2017-05-16 05:57:34
【问题描述】:
我正在运行简单的thread,其运行方法如下
public run()
while(!stopFlag){
// print something Line 1
// print something Line 2
// print something Line 3
// print something Line 4
}
如果我通过ExecutorService 运行这个线程
ExecutorService exs = Executors.newFixedThreadPool(5);
exs.execute(new MyThread));
我停止ExecutorService
exs.shutdown();
但这不会停止线程,因为标志未设置为 false。在another question related to same topic 中,我被要求正确处理调用 exs.shutdown() 时引起的 InterruptedException。 但在这种情况下,我没有做任何可能引发 InterruptedException 的操作。
处理这种情况的标准方法是什么?
更多问题 Sabir 给出的答案是“如果您的可运行对象对中断的响应不佳,那么除了关闭 JVM 之外,没有什么可以阻止它。”这似乎是我的情况。
但是如何引入InterruptedException的处理;如果我没有调用任何引发中断异常的方法?
【问题讨论】:
-
您没有显示足够的线程代码。此外,您显示的那一点不会编译。
-
检查线程是否被中断。即
while(!Thread.interrupted()) -
文档说:
This method does not wait for previously submitted tasks to * complete execution. Use awaitTermination * to do that. -
最主要的是,当您使用阻塞 api 时,它会抛出一个中断的异常。如果您没有使用阻塞 api,则必须检查线程是否被中断。然后如果它被打断了,退出你的循环,或者如果你愿意,甚至抛出一个被打断的异常。
标签: java multithreading threadpool executorservice