为什么socketRead0使线程处于RUNNABLE状态

时间:2018-07-24 10:31:19

标签: java multithreading sockets

我用Java Thread编写了一个简单的ECHO协议服务器。

这很简单:

ServerSocket serverSocket = new ServerSocket(7000, 0, InetAddress.getByName("127.0.0.1"));
while (true) {
    Socket socket = serverSocket.accept();
    new Thread(() -> {
        try (Socket s = socket;
             BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
             BufferedWriter out = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()))) {
            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                out.write(inputLine + '\n');
                out.flush();
            }
        } catch (IOException e) {
        }
    }).start();
}

该线程正在等待客户端在inputLine = in.readLine()上的输入。 但是我发现所有工作线程都通过RUNNABLE处于jstack状态,我认为它们可能处于WAITING状态。

线程在等待数据到达时被阻塞,但是为什么在这里RUNNABLE呢?

这是jstack的输出:

"Thread-0" #10 prio=5 os_prio=31 tid=0x00007f9f8282e800 nid=0x1307 runnable [0x000070000623a000]
 java.lang.Thread.State: RUNNABLE
  at java.net.SocketInputStream.socketRead0(Native Method)
  at java.net.SocketInputStream.socketRead(SocketInputStream.java:116)
  at java.net.SocketInputStream.read(SocketInputStream.java:170)
  at java.net.SocketInputStream.read(SocketInputStream.java:141)
  at sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:284)
  at sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:326)
  at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:178)
  - locked <0x000000076b167a18> (a java.io.InputStreamReader)
  at java.io.InputStreamReader.read(InputStreamReader.java:184)
  at java.io.BufferedReader.fill(BufferedReader.java:161)
  at java.io.BufferedReader.readLine(BufferedReader.java:324)
  - locked <0x000000076b167a18> (a java.io.InputStreamReader)
  at java.io.BufferedReader.readLine(BufferedReader.java:389)
  at EchoServer3.lambda$main$0(EchoServer3.java:20)

1 个答案:

答案 0 :(得分:1)

WAITING表示Java线程正在等待另一个Java线程释放Java对象锁。

Java不了解操作系统块,锁或调度。因此,可能会阻止Java线程等待输入的事实并不会影响Java对其状态的看法。