How to interrupt BufferedReader's readLine

后端 未结 9 1387
醉梦人生
醉梦人生 2020-11-29 07:56

I am trying to read input from a socket line by line in multiple threads. How can I interrupt readLine() so that I can gracefully stop the thread that it\'s bl

9条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-29 08:26

    A sketch for a solution might be this: NIO provides methods for nonblocking IO, so you have to implement something called Foo that uses nonblocking NIO on the socket end but also provides a InputStream or Reader interface on the other end. If the BufferedReader enters its own read, it will call Foo, which will call Selector.select with read intent. select will either return indicating the presence of more data or it will block until more data is available.

    If another thread wants to unblock the reader, it must call Selector.wakeup and the selector can return gracefully by throwing an exception the by BufferedReader.

    The socket should be still open after that.

    Variation A: call Selector.select(timeout) to do busy polling light.

提交回复
热议问题