我有一个多线程的 Java 服务。这是一个发布者-订阅者应用程序。
有一个消息总线,并且有几个监听消息总线的插件组件。来自插件的每个请求都由消息总线在单独的线程中处理。它作为 Windows 服务运行。
在stop方法中,当前我正在做的是调用System.exit(0)
。在其他几个类似的问题中,有些人说这是一种不好的做法,而另一些人则认为这是很好的做法。甚至 Sonarqube 也对此有所提示。
那么停止所有这些线程的优雅方法是什么?我应该对它们调用 Thread.interrupt 吗?
这些客户端持续监听消息总线,如果收到任何事件消息,它们就会对其进行处理。
最佳答案
使用 Thread.interrupt() 是一种完全可以接受的方法。原因是,如果您处于可中断的阻塞调用中(例如 Thread.sleep 或使用 java.nio Channel 操作),您实际上可以立即摆脱这些调用。
有关 SO question 和 here 的更多详细信息
更多详细说明请访问:here
Summary:
- thread.interrupt() does not stop a thread. It is used for coordination in multi-threaded programs. Don't use it unless you know exactly what you do.
- Throwing a RuntimeException will (usually) terminate the thread but not necessarily the program.
- System.exit(int) almost always terminates the program and returns a status code.
- In unusual situations, System.exit(int) might not actually stop the program.
- Runtime.getRuntime().halt(int) on the other hand, always does.
关于java - 停止运行多个线程的 Java 服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34553859/