2016-04-23 36 views
0

這個問題聽起來很奇怪,但我很想知道是否可以在執行程序時休息幾秒鐘。例如,當您有一個簡單的for()用於打印數組元素,元素將直接打印出來。我想知道是否可以像第一個元素那樣打印,然後在2秒鐘的間隔後打印第二個元素,直到最後一個。是這樣的可能嗎?如何在執行程序時休息幾秒鐘

+1

你應該看看 http://stackoverflow.com/questions/3342651/how-can-i-delay-a-java-program-for-a-few-seconds –

+0

了Thread.sleep(2000); ? https://docs.oracle.com/javase/tutorial/essential/concurrency/sleep.html – Devrim

+1

你可以使用Thread.currentThread()。sleep(),但不能保證睡眠2秒。可能會更多。或者你可以使用一個while循環,從當前時間減去最後一個值的打印時間,並查看差值是否爲2秒,然後打印下一個值。這是一個忙碌的等待,而另一個選項sleep()使處理器可以自由地執行其他任務。 – Madhusudhan

回答

1

只需添加Thread.sleep()。

for (...) { 
    //print the element 
    try { 
     Thread.sleep(2000); 
    } catch (InterruptedException e) { 
     //do things with exception 
    } 
} 
0

可以使用Thread.sleep(1000)方法在for循環:

public class JavaApp{ 

    public static void main(String[] args) { 
     for (int i = 0; i < 10; i++) { 
      System.out.println(i); 
      try { 
       Thread.sleep(1000); 
      } catch (Exception e) { 

      } 
     } 
    } 
} 

它從0到9,每秒一個號碼打印。

run: 
0 
1 
2 
3 
4 
5 
6 
7 
8 
9 
**BUILD SUCCESSFUL (total time: 10 seconds)** 
0

你可以用睡眠功能。

Thread.sleep(4000); // 4000 = 4 second 
0

我建議使用Thread.sleep()

試試這個:

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

這樣,程序將暫停1000毫秒。

+0

當發生這種異常? – EbraHim

+0

@EbraHim:在線程正在等待,休眠或以其他方式佔用線程並且線程中斷時,在活動之前或活動期間引發此異常。 –

0

Thread.currentThread.sleep(time in ms);

+1

請添加一些代碼的解釋或至少一個鏈接到編程參考或指南。 –