Java 停止/中断线程在等待来自套接字的输入时被阻塞
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1024482/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Stop/Interrupt threads blocked on waiting input from socket
提问by klaus johan
As the title says I need a way to stop or interrupt a thread that is blocked waiting on an input from the socket.
正如标题所说,我需要一种方法来停止或中断在等待来自套接字的输入时被阻塞的线程。
采纳答案by Kosi2801
Thread.interrupt()should be the method you're looking for. Be sure that your input-accessing methods also check for InterruptedException and ClosedByInterruptException.
Thread.interrupt()应该是您正在寻找的方法。确保您的输入访问方法也检查 InterruptedException 和 ClosedByInterruptException。
Also look at the corresponding page in the Sun Concurrency Tutorial, as another solution suggests.
另请参阅 Sun Concurrency Tutorial中的相应页面,正如另一种解决方案所建议的那样。
回答by Daniel Schneller
Sockets allow to set a timeout via the setSoTimeout()
method. This is the preferred way to stop them blocking.
套接字允许通过该setSoTimeout()
方法设置超时。这是阻止它们阻塞的首选方法。
Otherwise you might want to have a look at the nio
package which allows for non-blocking I/O at the expense of more manual work to manage incoming and outgoing data.
否则,您可能需要查看nio
允许非阻塞 I/O 的包,但需要更多的手动工作来管理传入和传出数据。
回答by akarnokd
You could simply close() the IO stream/socket from another thread. Then, you could check on a volatile boolean field if the resulting IOException is due the close or something else. I think the close might result in an java.net.SocketException: Socket closed
exception.
您可以简单地从另一个线程 close() IO 流/套接字。然后,如果结果 IOException 是由于关闭或其他原因,您可以检查 volatile 布尔字段。我认为关闭可能会导致java.net.SocketException: Socket closed
异常。
回答by Glenn
Try using sock.closeInput() followed by sock.close()
尝试使用 sock.closeInput() 后跟 sock.close()
回答by Bill Wohler
I didn't see socket.closeInput()
. However, I did find socket.shutdownInput()
. After calling that (from a different thread that was blocking on the read naturally), my call to bufferedReader.close()
worked fine! (I followed that with calls to printWriter.close()
and socket.close()
.
我没有看到socket.closeInput()
。不过,我确实找到了socket.shutdownInput()
。在调用它之后(从一个自然阻塞读取的不同线程),我的调用bufferedReader.close()
工作正常!(我随后调用了printWriter.close()
和socket.close()
。
回答by Alin
Close the socket and the read will be unblocked (will exit with a subclass of IOException). Read reacting to Thread.interrupt is platform dependent (won't work on Solaris 10 for example).
关闭套接字,读取将被解除阻塞(将以 IOException 的子类退出)。对 Thread.interrupt 做出反应的读取取决于平台(例如,在 Solaris 10 上不起作用)。