2014-06-08 155 views
126

我想在Java中做一些事情,我需要在while循環中等待/延遲一段時間。如何在Java中延遲?

while (true) { 
    if (i == 3) { 
     i = 0; 
    } 

    ceva[i].setSelected(true); 
    //need to wait here 
    ceva[i].setSelected(false); 
    //need to wait here 
    i++; 
} 

我想構建一個步進音序器,我是新來的Java。有什麼建議麼 ? 謝謝!

+11

使用'Thread.sleep代碼()'。 – Tiny

+0

考慮使用[Timer](http://docs.oracle.com/javase/7/docs/api/java/util/Timer.html) – PeterMmm

+0

等待的目的是什麼?你是否在等待某個事件發生?確保你明白[sleep()](http://docs.oracle.com/javase/tutorial/essential/concurrency/sleep.html)方法的作用 – artdanil

回答

283

如果要暫停,然後使用java.util.concurrent.TimeUnit

TimeUnit.SECONDS.sleep(1); 

睡一秒或

TimeUnit.MINUTES.sleep(1); 

睡了一分鐘。

由於這是一個循環,這提出了一個固有的問題 - 漂移。每次你運行代碼,然後睡覺,你將會跑步,比如說,每一秒都會跑步。如果這是一個問題,那麼請不要使用sleep。當涉及到控制時,sleep並不是非常靈活。

運行任務每秒或在一週秒鐘後我會強烈推薦ScheduledExecutorService,要麼scheduleAtFixedRatescheduleWithFixedDelay

例如,要運行的方法myTask每秒(爪哇8):

public static void main(String[] args) { 
    final ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor(); 
    executorService.scheduleAtFixedRate(App::myTask, 0, 1, TimeUnit.SECONDS); 
} 

private static void myTask() { 
    System.out.println("Running"); 
} 

而在爪哇7:

public static void main(String[] args) { 
    final ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor(); 
    executorService.scheduleAtFixedRate(new Runnable() { 
     @Override 
     public void run() { 
      myTask(); 
     } 
    }, 0, 1, TimeUnit.SECONDS); 
} 

private static void myTask() { 
    System.out.println("Running"); 
} 
+0

@Matthew Moisen我無法得到這個Java 8的例子運行。什麼是App ::究竟是什麼?通過將myTask()更改爲可運行的lambda它可以工作:Runnable myTask =() - > {...}; – comfytoday

+1

這是一個方法參考@comfytoday - 我建議從[文檔](https://docs.oracle.com/javase/tutorial/java/javaOO/methodreferences.html)開始。 –

+0

'TimeUnit.SECONDS.wait(1)'在Windows 6.3上的Java 8.1 build 31中拋出'IllegalMonitorStateException'。相反,我可以在沒有try/catch的情況下使用'Thread.sleep(1000)'。 –

62

使用了Thread.sleep(1000);

1000是程序暫停的毫秒數。

try   
{ 
    Thread.sleep(1000); 
} 
catch(InterruptedException ex) 
{ 
    Thread.currentThread().interrupt(); 
} 
+2

不要忘記記錄InterruptedException,否則你永遠不會知道這個線程被中斷。 – m0skit0