ServerSocket 被从控制台寻求输入的线程阻塞
谁能告诉我为什么 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我不认为阻塞的是 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.
从 System.in 读取会导致很多问题:
在某些情况下,您不能:
我在 Windows Server 2003 及更早版本中遇到过一些此类问题。发生这种情况是因为 Win32-API 和 Java-VM 中的一些错误。
但可能有一个简单的解决方法:
如果 System.in.availiable() 返回大于 0 的值,则仅调用 System.in.read()。
System.loadLibrary() 和
System.in.read()
间歇性挂起
在 Win32 中
Reading from System.in causes a lot of problems:
Under some circumstances you can't:
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.
System.loadLibrary() and
System.in.read()
hanging intermittenly
in Win32