asm*_*smo 47 java multithreading netbeans sleep hint
在NetBeans中,有一个新提示:Thread.sleep在循环中调用.
问题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();
}
}
Run Code Online (Sandbox Code Playgroud)
Ste*_*n C 22
在循环中调用睡眠通常会导致性能不佳.例如:
while (true) {
if (stream.available() > 0) {
// read input
}
sleep(MILLISECONDS);
}
Run Code Online (Sandbox Code Playgroud)
如果MILLISECONDS太大,则此代码将花费很长时间才能意识到输入可用.
如果MILLISECONDS太小,那么此代码将浪费大量系统资源检查尚未到达的输入.
sleep
循环中的其他用途通常也是有问题的.通常有更好的方法.
如果这是一个问题,我该怎么做呢?
发布代码,也许我们可以给你一个明智的答案.
编辑
IMO,解决问题的更好方法是使用a ThreadPoolExecutor
.
像这样的东西:
public void listen() {
BlockingQueue queue = new SynchronousQueue();
ThreadPoolExecutor executor = new ThreadPoolExecutor(
1, Session.getMaxSessionCount(), 100, TimeUnit.SECONDS, queue);
while (true) {
try {
queue.submit(new Session(database, serverSocket.accept()));
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
Run Code Online (Sandbox Code Playgroud)
这会将执行程序配置为与您的代码当前的工作方式相匹配.还有很多其他方法可以做到; 请参阅上面的javadoc链接.
正如其他人所说,这取决于用法。合法的用途是设计为每 10 秒执行一次操作的程序(但并不重要到需要精确的计时)。我们有很多这样的“实用应用程序”,每隔几分钟就会导入数据和其他此类任务。这是执行这些任务的简单方法,我们通常会将睡眠间隔设置得非常低并使用计数器,以便程序保持响应并可以轻松退出。
int count = 0;
while (true) {
try {
// Wait for 1 second.
Thread.sleep(1000);
}
catch (InterruptedException ex) {}
// Check to see if the program should exit due to other conditions.
if (shouldExit())
break;
// Is 10 seconds up yet? If not, just loop back around.
count++;
if (count < 10) continue;
// 10 seconds is up. Reset the counter and do something important.
count = 0;
this.doSomething();
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
40744 次 |
最近记录: |