2013-12-14 33 views
-1

我需要一個變量向上計數,但增量爲2秒。現在我只是使用++;函數,但正如你所知它非常快。有沒有辦法減慢變量++;功能?

有什麼簡單的我可以用來計算速度較慢?

+3

'的Thread.sleep(2000 )'但它不準確。您可能想要更類似於'Timer'的東西 – clcto

+0

同意@clcto,您應該閱讀[Java:如何使用Timer類調用方法,執行某些操作,重置計時器,重複?](http://stackoverflow.com/問題/ 9413656/java-how-to-use-timer-class-to-call-a-method-do-something-reset-timer-repeat)可能對你有所幫助。 – Smit

回答

1
Thread.sleep(2000); 

這會讓你的程序在這個方法調用和緊隨其後的任何執行行之間等待2秒鐘。

0

是的,您可以使用Thread.sleep(2000)暫停執行兩秒鐘。

//Your code... 
Thread.sleep(2000); 
counter = counter + 2; 
//Your code... 
0

這將打印從1到99,遞增2之間,增量之間暫停一秒。

public static void main(String[] args) { 
    for (int i = 1; i < 100; i += 2) { // i = i + 2 
    System.out.printf("i = %d\n", i); // print i = # 
    try { 
     Thread.sleep(2000); // two seconds. 
    } catch (InterruptedException e) { 
    } 
    } 
} 
1
public class Count implements Runnable{ 
    public void run(){ 
    for(int i=0;i<=6;i+=2){ 
     Thread.sleep(2000)//in milliseconds ...sleeping for 2 sec 
     sysout(...);//print your value 
     } 
    } 
} 

開始就這樣

Runnable r=new Count(); 
Thread t=new Thread(r); 
t.start(); // start the thread 

你在做什麼是basicly做一個線程,並用delay.I運行希望你得到一個概念

+0

+1,你不應該在主線程上使用'Thread.sleep()'。 –

相關問題