如何将while循环延迟到1秒间隔,而不会使运行的整个代码/计算机减速到一秒延迟(只有一个小循环)。
答案 0 :(得分:26)
Thread.sleep(1000); // do nothing for 1000 miliseconds (1 second)
答案 1 :(得分:11)
似乎你的循环在主线程上运行,如果你在该线程上执行sleep
,它将暂停应用程序(因为只有一个线程已被暂停),为了解决这个问题,你可以将这些代码放入并行运行的新Thread
try{
Thread.sleep(1000);
}catch(InterruptedException ex){
//do stuff
}
答案 2 :(得分:2)
我推迟循环的简单方法。
在没有遵循stackoverflow的标准后,我已将代码放在此处。
//1st way: Thread.sleep : Less efficient compared to 2nd
try {
while (true) {//Or any Loops
//Do Something
Thread.sleep(sleeptime);//Sample: Thread.sleep(1000); 1 second sleep
}
} catch (InterruptedException ex) {
//SomeFishCatching
}
//================================== Thread.sleep
//2nd way: Object lock waiting = Most efficient due to Object level Sync.
Object obj = new Object();
try {
synchronized (obj) {
while (true) {//Or any Loops
//Do Something
obj.wait(sleeptime);//Sample obj.wait(1000); 1 second sleep
}
}
} catch (InterruptedException ex) {
//SomeFishCatching
}
//=============================== Object lock waiting
//3rd way: Loop waiting = less efficient but most accurate than the two.
long expectedtime = System.currentTimeMillis();
while (true) {//Or any Loops
while(System.currentTimeMillis() < expectedtime){
//Empty Loop
}
expectedtime += sleeptime;//Sample expectedtime += 1000; 1 second sleep
//Do Something
}
//===================================== Loop waiting
答案 3 :(得分:1)
正如Jigar所说,你可以使用另一个Thread来做可以独立于其他线程操作,睡眠等工作。 java.util.Timer
类可能对您有所帮助,因为它可以为您执行定期任务,而无需进入多线程编程。