ServerSocket blocked by thread seeking input from console

*爱你&永不变心* 提交于 2019-12-11 01:25:20

问题


Can anyone give me insight into why the ServerSocket constructor never returns in the new thread? (I never see the "Opened" message printed to the console.) It seems the main thread prevents the server socket thread from running by entering into readLine too quickly:

public class Main
{
   public static void main(String[] args) throws IOException
   {
      new Thread(new SocketOpener()).start();

      BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
      String inLine = br.readLine();
      System.out.println(inLine);
   }
}

public class SocketOpener implements Runnable
{

   public void run()
   {
      try
      {
         System.out.println("Opening...");
         ServerSocket socket = new ServerSocket(4444);
         System.out.println("Opened");
      }
      catch (IOException ex)
      {
         System.out.println("IO Error");
      }
   }

}

回答1:


I don't think that it's the ServerSocket constructor that blocks, but the System.out.println("Opened"). The fact that the main thread is trying to read from System.in prevents outputs to be done on System.out.




回答2:


Reading from System.in causes a lot of problems: Under some circumstances you can't:

  1. Create a Temp-File (because of 2)
  2. Read the Inet4Adress of your maschine
  3. Load a DLL

I've encountert some of this Problems with Windows Server 2003 and older. This happens because of some Bugs in the Win32-API ans Java-VM.

But there may be an easy workarround:

Only call System.in.read(), if System.in.availiable() returns a value larger than 0.

  • Deadlock between System.loadLibrary() and System.in.read()
  • Inet4AddressImpl.getLocalHostName is hanging intermittenly
  • Deadlock in Win32


来源:https://stackoverflow.com/questions/3836780/serversocket-blocked-by-thread-seeking-input-from-console

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!