在等待连接的过程中,一个线程究竟挂在serversocket.accept()的什么位置?

kyks70gy  于 2021-06-30  发布在  Java
关注(0)|答案(1)|浏览(302)

在下面的代码块中,我知道这个主线程是阻塞的,因此没有监听来自其他线程的中断,但这是否意味着它实际上挂在serversocket.accept()行上?

ServerSocket serverSocket = new ServerSocket(8080);

        while(true){ // Block until accept
            Socket acceptedSocket = serverSocket.accept(); // Give accepted socket OR NULL SOCKET to acceptedSocket

            handle(acceptedSocket);

            serverSocket.close();
        }

我问这个问题是因为我不明白在accept(serversocket.java)上它会挂在哪里:

public Socket accept() throws IOException {
        if (isClosed()) // No its open
            throw new SocketException("Socket is closed");
        if (!isBound())   // No its bound to 8080
            throw new SocketException("Socket is not bound yet");
        Socket s = new Socket((SocketImpl) null);                  // Create a null socket
        implAccept(s);                                          // Here???
        return s;
    }

serversocket.java再次:

protected final void implAccept(Socket s) throws IOException {

  SocketImpl si = null;
    try {
        if (s.impl == null)
          s.setImpl();
        else {
            s.impl.reset();
        }
        si = s.impl;
        s.impl = null;
        si.address = new InetAddress();
        si.fd = new FileDescriptor();
        getImpl().accept(si);    // I'm thinking its here but when I look at this accept, thats an abstract method and don't know where to dig deeper.
oyjwcjzk

oyjwcjzk1#

取决于操作系统,但在linux上,accept()是一个内核调用。最严格的java实现是使用内核调用。
所以这个过程是“在内核中等待”,粗略地说。

相关问题