我可以杀死一个正在等待 TCP 连接的线程吗?
我有一个应用程序,其中一个线程正在侦听 TCP 连接,需要将其终止。最好的方法是什么?我知道 Thread.stop 已被弃用,中断线程就足够了吗?
I have a application where a thread is listening for TCP connections, and will need to be killed. What is the best way to do this? I know that Thread.stop is deprecated, is interrupting the thread enough?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您有对
ServerSocket
的引用,您可以调用它的close()
方法。这将导致等待accept()
的线程抛出SocketException
。请注意,您可能不想公开对套接字本身的引用;您可能应该在服务器代码中添加一个名为
shutdownServer()
的方法或类似的方法,该方法本身会执行此操作。If you have a reference to a
ServerSocket
you can call itsclose()
method. This will cause the Thread waiting onaccept()
to throw aSocketException
.Note that you probably don't want to expose a reference to the socket itself; you should probably add a method to your server code named
shutdownServer()
or similar which does this itself.一般来说 - 是的,您应该使用 Thread.interrupt() 和共享变量。在您的特定示例中,您可以关闭 Socket 以使线程立即返回。请在此处阅读相关内容。
Generally - yes, you should use Thread.interrupt() and a shared variable. In your particular example, you can just close the Socket to cause the thread to return immediately. Read about it here.
您可以设置一个“停止”变量,线程在每次连接后检查该变量。然后连接到线程的端口将其唤醒。
另一种方法是通过调用 soTimeout() 来设置超时,并在每次连接后以及超时发生时检查“stop”变量。您可能不想将超时设置得太短。这意味着线程不会立即停止,因此如果需要快速关闭,这可能对您不起作用。
如果可能的话,您还可以直接在 ServerSocket 上调用 close(),如 Mark Peters 所提到的。
You could set a "stop" variable that the thread checks after each connection. Then connect to the thread's port to wake it up.
Another approach would be to set a timeout with a call to
soTimeout()
and check the "stop" variable after each connection and when the timeout occurs. You probably don't want to set the timeout too short. This means the thread would not stop immediately, so that might not work for you if a quick shutdown is required.You could also call close() directly on the ServerSocket if possible as mentioned by Mark Peters.