Java读取socket时中断线程
可能的重复:
如何终止套接字 IO 操作上的线程阻塞立即?
我有一个客户端在线程中运行,想要从 Java 中的套接字读取数据。但在阅读时,也许我想杀死线程。所以我中断
它,但是套接字的读取方法会抛出InterruptedException
吗?我没找到。
那么,当线程在读取套接字时阻塞时,我怎样才能很好地要求线程终止呢?
谢谢
Possible Duplicate:
How to terminate a thread blocking on socket IO operation instantly?
I have client run in thread want to read from socket in Java. But while reading, maybe I want to kill the thread. So I interrupt
it, but does socket's reading methods throw InterruptedException
? I didn't find.
So, how can I nicely ask thread to die while it's blocking on reading socket?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
已回答如何终止线程阻塞立即进行套接字 IO 操作?
基本上,当您
close()
套接字时,所有关联的流都将关闭,从而导致所有被阻止的操作被解除阻止。或者您可以调用 Thread.interrupt() ,它将中断阻塞操作,导致抛出 InterruptedException 。
It has been answered How to terminate a thread blocking on socket IO operation instantly?
Basically, when you
close()
the socket, all the associated streams will close, causing all the blocked operations to be unblocked.Or you can call
Thread.interrupt()
and it will interrupt the blocking operation causing it to throw theInterruptedException
.NIO 通道具有 InterruptableChannel,其中将在阻塞操作时被中断。您可以将 NIO 与阻塞操作一起使用,因此它们的工作方式与 Java IO 非常相似,即您无需重新开发应用程序即可使用选择器/调度程序等。
The NIO Channels have InterruptableChannels which will be interrupted on blocking operations. You can use NIO with blocking operations so they work much the same as Java IO i.e. you don't have to redevelop your application to use Selectors/Dispatchers etc.