2015-04-15 122 views
0

所以有這樣的代碼,其計數到21,但我想使3第二定時器對每個數目是這樣的:
3秒後
3秒後
3秒鐘之後

像這樣,這裏是我的代碼,如果你有任何想法,你能幫我做點什麼嗎?爪哇定時器代碼

package me.Capz.While; 

public class WhileLoop { 

    public static void main(String args[]) { 

     double money = 0; 

     while (money < 22) { 

      System.out.println(money); 

      money++; 

     } 
    } 
} 
+1

把'主題。循環體中的.sleep(3000)'(並酌情添加'throws'或'try' /'catch')。 – aioobe

+0

您不會像您在描述中所述的那樣從1開始。在println之前使用money ++作爲第一個輸出打印1。 – RaphMclee

回答

0

下方的用戶code.This將暫停3秒。

System.out.println(money); 
Thread.sleep(3000); 
0
public static void main(String args[]) throws InterruptedException { 
    double money = 0; 
    while (money < 22) { 
     System.out.println(money); 
     money++; 
     Thread.sleep(3000); 
    } 
} 
2

可能做到這一點最簡單的方法是使用Thread#sleep(long)

package me.Capz.While; 

public class WhileLoop { 

    public static void main(String args[]) { 

     double money = 0; 

     while (money < 22) { 
      System.out.println(money); 
      money++; 
      try { 
       Thread.sleep(3000L); // The number of milliseconds to sleep for 
      } catch (InterruptedException e) { 
       // Some exception handling code here. 
      } 
     } 
    } 
} 
1

這是你的問題陳述的異步非阻塞的解決方案:

public static void main(String[] args) { 
    printAndSchedule(1); 
} 

public static void printAndSchedule(final int money) { 
    if (money < 22) { 
     System.out.println(money); 
     new Timer().schedule(new TimerTask() { 
      public void run() { 
       printAndSchedule(money + 1); 
      } 
     }, TimeUnit.SECONDS.toMillis(3)); 
    } 
} 
+0

總是很高興看到替代解決方案 – JonK