Stop/Interrupt threads blocked on waiting input from socket

后端 未结 6 1785
自闭症患者
自闭症患者 2021-01-04 04:12

As the title says I need a way to stop or interrupt a thread that is blocked waiting on an input from the socket.

相关标签:
6条回答
  • 2021-01-04 04:41

    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().

    0 讨论(0)
  • 2021-01-04 04:52

    Try using sock.closeInput() followed by sock.close()

    0 讨论(0)
  • 2021-01-04 04:54

    Thread.interrupt() should be the method you're looking for. Be sure that your input-accessing methods also check for InterruptedException and ClosedByInterruptException.

    Also look at the corresponding page in the Sun Concurrency Tutorial, as another solution suggests.

    0 讨论(0)
  • 2021-01-04 04:55

    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).

    0 讨论(0)
  • 2021-01-04 04:56

    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.

    0 讨论(0)
  • 2021-01-04 04:57

    Sockets allow to set a timeout via the setSoTimeout() method. This is the preferred way to stop them blocking.

    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.

    0 讨论(0)
提交回复
热议问题