Java延迟/等待

如何将while循环延迟到1秒间隔,而不会将运行的整个代码/计算机减慢到一秒钟的延迟(只有一个小循环)。

Thread.sleep(1000); // do nothing for 1000 miliseconds (1 second)

看起来你的循环在主线程上运行,如果你在该线程上sleep ,它将暂停应用程序(因为只有一个线程已被暂停),为了克服这一点,你可以把这个代码放在并行运行的新Thread

 try{ Thread.sleep(1000); }catch(InterruptedException ex){ //do stuff } 

我简单的延迟循环的方法。

我没有遵循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 

正如Jigar已经指出你可以使用另一个Thread来做可以独立于其他线程操作,睡眠等工作。 java.util.Timer类可能对您有所帮助,因为它可以为您执行定期任务,而无需进入multithreading编程。