谁能告诉我为什么 ServerSocket 构造函数永远不会在新线程中返回?(我从来没有看到打印到控制台的“打开”消息。)似乎主线程通过太快地进入 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");
}
}
}