为什么这个循环第一次执行,然后等待直到if
子句中的条件为真?
Random rand = new Random();
int i = 0;
while (true) {
currencyList.put(Currency.EUR, BigDecimal.valueOf(7*rand.nextDouble()+1.2));
currencyList.put(Currency.HRK, BigDecimal.valueOf(7*rand.nextDouble()+1.2));
currencyList.put(Currency.NOK, BigDecimal.valueOf(7*rand.nextDouble()+1.2));
currencyList.put(Currency.USD, BigDecimal.valueOf(7*rand.nextDouble()+1.2));
System.out.println(currencyList);
Socket sock = null;
if ( (sock = serversocket.accept()) != null) {
System.out.println("Client " + (++i) + "connected...");
new ServerThreadB(sock,username).start();
}
}
答案 0 :(得分:2)
阅读文档,它说"方法会阻塞,直到建立连接。":https://docs.oracle.com/javase/7/docs/api/java/net/ServerSocket.html#accept()
答案 1 :(得分:1)
ServerSocket阻止程序继续进行,直到建立连接。
要限制程序停止的时间,您可以使用setSoTimeout(long milli)方法(以毫秒为单位)来确定套接字放弃所需的时间。