开发者

Java interrupt thread when reading socket [duplicate]

开发者 https://www.devze.com 2023-03-09 04:57 出处:网络
This question already has answers here: Closed 11 years ago. Possible Duplicate: How to terminate a thread blocking on socket IO operation inst开发者_Python百科antly?
This question already has answers here: Closed 11 years ago.

Possible Duplicate:

How to terminate a thread blocking on socket IO operation inst开发者_Python百科antly?

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


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 the InterruptedException.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号