在 NetBeans 中,有一个新提示:Thread.sleep call in loop。
问题 1:循环睡眠如何/何时会成为问题?
问题2:如果有问题,我应该怎么做?
更新:问题 3:这是一些代码。在这种情况下告诉我是否应该在循环中使用其他东西而不是 Thread.Sleep。简而言之,这是由侦听客户端 TCP 连接的服务器使用的。如果达到与客户端的最大会话数,则在此处使用睡眠。在这种情况下,我希望应用程序等到空闲会话可用。
public class SessionManager {
private static final int DEFAULT_PORT = 7500;
private static final int SLEEP_TIME = 200;
private final DatabaseManager database = new DatabaseManager();
private final ServerSocket serverSocket = new ServerSocket(DEFAULT_PORT);
public SessionManager() throws IOException, SQLException
{
}
public void listen()
{
while (true)
if (Session.getSessionCount() < Session.getMaxSessionCount())
try
{
new Thread(new Session(database, serverSocket.accept())).start();
}
catch (IOException ex) { ex.printStackTrace(); }
else
try
{
Thread.sleep(SLEEP_TIME);
}
catch (InterruptedException ex) { ex.printStackTrace(); }
}
public static void main(String[] args) throws IOException, SQLException
{
new SessionManager().listen();
}
}