0

独自のクラスメソッドを使用して、一定時間実行を停止するオブジェクトを作成する必要があります。プログラムに経過時間を追跡させ、指定された時間が経過したときに関数を実行させるにはどうすればよいですか。

私は想像する .......

long pause; //a variable storing pause length in milliseconds.............
long currentTime; // which store the time of execution of the pause ,............. 

また、別の可変追跡時間がcurrentTime + pauseと同じ値になると、次のコード行が実行されます。時間の経過とともにミリ秒ごとに短時間変化する変数を作成することは可能ですか?

4

1 に答える 1

2

簡単な解決策として、Thread#sleep

public void waitForExecution(long pause) throws InterruptedException { 
    // Perform some actions...
    Thread.sleep(pause);
    // Perform next set of actions
}

タイマー付き...

public class TimerTest {

    public static void main(String[] args) {
        Timer timer = new Timer("Happy", false);
        timer.schedule(new TimerTask() {

            @Override
            public void run() {
                System.out.println("Hello, I'm from the future!");
            }
        }, 5000);

        System.out.println("Hello, I'm from the present");
    }
}

そしてループで

long startAt = System.currentTimeMillis();
long pause = 5000;
System.out.println(DateFormat.getTimeInstance().format(new Date()));
while ((startAt + pause) > System.currentTimeMillis()) {
    // Waiting...
}
System.out.println(DateFormat.getTimeInstance().format(new Date()));

ループがCPUサイクルを消費し続けるため、これは他の2つのソリューションよりもコストがかかることに注意してください。一方、スレッドがアイドル状態になる(サイクルを消費しない)内部スケジューリングメカニズムThread#sleepTimer使用する

于 2012-11-14T05:25:02.337 に答える