NetBeans / Java / 新提示:在循环中调用 Thread.sleep
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3535754/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
NetBeans / Java / New hint: Thread.sleep called in loop
提问by asmo
In NetBeans, there's a new hint that says: Thread.sleep called in loop.
在 NetBeans 中,有一个新提示说:Thread.sleep 在循环中调用。
Question 1:How/when can it be a problem to sleep in a loop?
问题 1:循环睡眠如何/何时会成为问题?
Question 2:If it's a problem, what should I do instead?
问题2:如果有问题,我应该怎么做?
UPDATE: Question 3:Here's some code. Tell me in this case if I should be using something else instead of Thread.Sleep in a loop. In short, this is used by a server which listens for client TCP connections. The sleep is used here in case the max number of sessions with clients is reached. In this situation, I want the application to wait until a free session becomes available.
更新:问题 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();
}
}
采纳答案by Stephen C
Calling sleep in a loop typically leads to poor performance. For example:
在循环中调用 sleep 通常会导致性能不佳。例如:
while (true) {
if (stream.available() > 0) {
// read input
}
sleep(MILLISECONDS);
}
If MILLISECONDS is too large, then this code will take a long time to realize that input is available.
如果 MILLISECONDS 太大,则此代码将需要很长时间才能意识到输入可用。
If MILLISECONDS is too small, then this code will waste a lot of system resources check for input that hasn't arrived yet.
如果 MILLISECONDS 太小,那么此代码将浪费大量系统资源检查尚未到达的输入。
Other uses of sleep
in a loop are typically questionable as well. There's usually a better way.
sleep
循环中的其他用法通常也有问题。通常有更好的方法。
If it's a problem, what should I do instead?
如果这是一个问题,我应该怎么做?
Post the code and maybe we can give you a sensible answer.
发布代码,也许我们可以给你一个明智的答案。
EDIT
编辑
IMO, a better way to solve the problem is to use a ThreadPoolExecutor
.
IMO,解决问题的更好方法是使用ThreadPoolExecutor
.
Something like this:
像这样的东西:
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();
}
}
}
This configures the executor to match the way your code currently works. There are a number of other ways you could do it; see the javadoc link above.
这将配置执行程序以匹配您的代码当前的工作方式。有许多其他方法可以做到;请参阅上面的 javadoc 链接。
回答by Nikita Rybak
How/when can it be a problem to sleep in a loop?
People sometimes employ it in place of proper synchronization methods (like wait/notify).
循环睡眠如何/何时会成为问题?
人们有时会使用它来代替适当的同步方法(如等待/通知)。
If it's a problem, what should I do instead?
Depends on what you're doing. Although it's dificult for me to imagine situation where doing this is the best approach, I guess that's possible too.
如果这是一个问题,我应该怎么做?
取决于你在做什么。虽然我很难想象这样做是最好的方法的情况,但我想这也是可能的。
You can check Sun's concurrency tutorialon this subject.
您可以查看有关此主题的Sun 并发教程。
回答by java nut
As others have said it depends on the usage. A legitimate use would be a program that is designed to do something every 10 seconds (but is not so critical that exact timing is needed). We have lots of these "utility apps" that import data and other such tasks every few minutes. This is an easy way to perform these tasks and we typically will set the sleep interval to be very low and use a counter so that the program stays responsive and can exit easily.
正如其他人所说,这取决于用法。一个合法的用途是一个被设计为每 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();
}
回答by Ondrej Bozek
I think I come across one completely legitimate use of sleep()
method in loop.
我想我sleep()
在循环中遇到了一种完全合法的方法使用。
We have one-way connection between server and client. So when client wants to achieve asynchronous communication with server, he sends message to the server and than periodically polls for some response from server. There needs to be some Timeout interval.
我们在服务器和客户端之间建立了单向连接。因此,当客户端想要与服务器实现异步通信时,他会向服务器发送消息,然后定期轮询服务器的某些响应。需要有一些超时间隔。
Response resp = null;
for (int i = 0; i < POLL_REPEAT && resp == null; i++) {
try {
Thread.sleep(POLL_INTERVAL);
} catch (InterruptedException ie) {
}
resp = server.getResponse(workflowId);
}
POLL_REPEAT
* POLL_INTERVAL
~ TIMEOUT interval
POLL_REPEAT
* POLL_INTERVAL
~ 超时间隔