从另一个线程安全地关闭线程读取套接字输入流

时间:2014-05-13 04:30:12

标签: java multithreading sockets inputstream

我有一个线程从套接字的输入流中读取BufferedReader in。它运行在下面显示的while循环中。我还有一个PrintWriter out,它位于自己独立的线程中。

/*One thread*/
try {
    while ((line = in.readLine()) != null) {
        //do stuff
    }
} catch (IOException e) {
    e.printStackTrace();
} finally {
    try {
        in.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

/*Second thread*/
try {
    out.println("stuff");
} catch (InterruptedException e) {
    e.printStackTrace();
} finally {
    out.close();
}

当用户请求断开连接(正在单独的线程中处理)时,我想安全地关闭从流中读取的这些线程。

当我尝试关闭socket(一个静态变量)时,我相信它也应该关闭输入和输出流。

/*Third thread trying to stop the other threads so it can execute something*/
try {
    socket.close();
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
Thread1.join();
Thread2.join();
//Now do something else after the first two threads are done

但是,我的程序抛出一个SocketException并指向line = in.readLine())!=null

java.net.SocketException: socket closed
    at java.net.SocketInputStream.socketRead0(Native Method)
    at java.net.SocketInputStream.read(Unknown Source)
    at java.net.SocketInputStream.read(Unknown Source)
    at sun.nio.cs.StreamDecoder.readBytes(Unknown Source)
    at sun.nio.cs.StreamDecoder.implRead(Unknown Source)
    at sun.nio.cs.StreamDecoder.read(Unknown Source)
    at java.io.InputStreamReader.read(Unknown Source)
    at java.io.BufferedReader.fill(Unknown Source)
    at java.io.BufferedReader.readLine(Unknown Source)
    at java.io.BufferedReader.readLine(Unknown Source)

它确实断开连接,但我怎样才能安全地执行它以便不抛出SocketException?我做错了什么?

1 个答案:

答案 0 :(得分:5)

关闭另一个线程中被阻塞读取的套接字的正确方法是将其关闭以进行输入。这将为读取线程提供一个EOS,这将导致它关闭套接字并退出。