ServerSocket 被从控制台寻求输入的线程阻塞

发布于 2024-09-25 12:11:58 字数 756 浏览 0 评论 0原文

谁能告诉我为什么 ServerSocket 构造函数永远不会在新线程中返回? (我从未看到“Opened”消息打印到控制台。)似乎主线程通过过快地进入 readLine 来阻止服务器套接字线程运行:

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");
      }
   }

}

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");
      }
   }

}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

甜妞爱困 2024-10-02 12:11:58

我不认为阻塞的是 ServerSocket 构造函数,而是 System.out.println("Opened")。主线程尝试从 System.in 读取的事实阻止了在 System.out 上完成输出。

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.

雨落星ぅ辰 2024-10-02 12:11:58

从 System.in 读取会导致很多问题:
在某些情况下,您不能:

  1. 创建临时文件(因为 2)
  2. 读取机器的 Inet4Adress
  3. 加载 DLL

我在 Windows Server 2003 及更早版本中遇到过一些此类问题。发生这种情况是因为 Win32-API 和 Java-VM 中的一些错误。

但可能有一个简单的解决方法:

如果 System.in.availiable() 返回大于 0 的值,则仅调用 System.in.read()。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文