在 Java 中中断线程
我想优雅地关闭线程.我在互联网上看到了很多代码,并在这里查询.我认为有两种关闭方法.
I want to gracefully shutdown the threads. I seen many codes on internet and have query here. I think there are two approaches to shutdown.
- 使用布尔标志.一旦标记更改,我们就可以在 run 方法中破坏那里的代码.
- 使用中断方法.
我的问题是为什么避免使用布尔标志来优雅地关闭线程,当我运行示例程序时它运行良好.
My question why it is avoided to use boolean flag to gracefully shutdown the threads, When I ran sample program it went well.
boolean
标志没有任何问题,但是:
There is nothing wrong with boolean
flag, however:
你需要记住同步/可见性(至少把
volatile
放在标志上)
为什么在已经实现(中断
)的情况下添加一个额外的标志?
why adding an extra flag when one is already implemented (interrupted
)?
其他库/容器可能会尝试中断您的线程(毕竟,他们不知道您的标志!)所以您仍然需要支持 InterruptedException
和/或 isInterrupted()
标志
Other libraries/containers might try to interrupt your thread (after all, they don't know about your flag!) so you still need to support InterruptedException
and/or isInterrupted()
flag
中断线程也可以中断 I/O 调用和 Thread.sleep()
.您的自定义标志不能
interrupting a thread can also interrupt I/O calls and Thread.sleep()
. Your custom flag can't