23

いくつかのプロセスを担当するスレッドがあります。これらの処理が3秒ごとに行われるようにしたい。以下のコードを使用しましたが、スレッドが開始しても何も起こりません。タイマーのタスクを定義すると、ScheduledTask時間間隔内で自動的に実行されると想定しましたが、何もしません。私は何が欠けていますか?

class temperatureUp extends Thread 
{
    @Override
    public void run()
    {
    TimerTask increaseTemperature = new TimerTask(){

        public void run() {
        try {
            //do the processing 
        } catch (InterruptedException ex) {}
        }
    };

    Timer increaserTimer = new Timer("MyTimer");
    increaserTimer.schedule(increaseTemperature, 3000);

    }
};
4

5 に答える 5

26

コード スニペットのいくつかのエラー:

  • クラスを拡張しますがThread、これはあまり良い習慣ではありません
  • Timer内に がありますThreadか? Timeraは単独で実行されるため、意味がありませんThread

むしろ(必要な場合/必要に応じて)実装する必要がありますが、短い例についてはこちらRunnableを参照してください。ThreadTimer

Timer呼び出されるたびに (3 秒ごとに) 単純にカウンターを 1 ずつインクリメントする動作の例を以下に示します。

import java.util.Timer;
import java.util.TimerTask;

public class Test {

    static int counter = 0;

    public static void main(String[] args) {

        TimerTask timerTask = new TimerTask() {

            @Override
            public void run() {
                System.out.println("TimerTask executing counter is: " + counter);
                counter++;//increments the counter
            }
        };

        Timer timer = new Timer("MyTimer");//create a new Timer

        timer.scheduleAtFixedRate(timerTask, 30, 3000);//this line starts the timer at the same time its executed
    }
}

補遺:

Threadをミックスに組み込む簡単な例を示しました。したがって、は3 秒ごとに 1TimerTaskだけインクリメントし、はカウンターをチェックするたびに 1 秒間スリープしている s 値を表示します (それ自体とタイマーは の後に終了します):counterThreadcountercounter==3

import java.util.Timer;
import java.util.TimerTask;

public class Test {

    static int counter = 0;
    static Timer timer;

    public static void main(String[] args) {

        //create timer task to increment counter
        TimerTask timerTask = new TimerTask() {

            @Override
            public void run() {
                // System.out.println("TimerTask executing counter is: " + counter);
                counter++;
            }
        };

        //create thread to print counter value
        Thread t = new Thread(new Runnable() {

            @Override
            public void run() {
                while (true) {
                    try {
                        System.out.println("Thread reading counter is: " + counter);
                        if (counter == 3) {
                            System.out.println("Counter has reached 3 now will terminate");
                            timer.cancel();//end the timer
                            break;//end this loop
                        }
                        Thread.sleep(1000);
                    } catch (InterruptedException ex) {
                        ex.printStackTrace();
                    }
                }
            }
        });

        timer = new Timer("MyTimer");//create a new timer
        timer.scheduleAtFixedRate(timerTask, 30, 3000);//start timer in 30ms to increment  counter

        t.start();//start thread to display counter
    }
}
于 2012-07-29T09:03:48.480 に答える
3

3 秒ごとに何かを行うには、scheduleAtFixedRate を使用する必要があります ( javadocを参照)。

ただし、スレッドの実行が停止する直前にタイマーを開始するスレッドを作成するため、コードは実際には何もしません (これ以上行うことはありません)。タイマー (シングル シュート 1) がトリガーされると、中断するスレッドはありません (以前に終了した実行)。

class temperatureUp extends Thread 
{
    @Override
    public void run()
    {
    TimerTask increaseTemperature = new TimerTask(){

        public void run() {
        try {
            //do the processing 
        } catch (InterruptedException ex) {}
        }
    };

    Timer increaserTimer = new Timer("MyTimer");
    //start a 3 seconds timer 10ms later
    increaserTimer.scheduleAtFixedRate(increaseTemperature, 3000, 10);

    while(true) {
         //give it some time to see timer triggering
         doSomethingMeaningful();
    }
}
于 2012-07-29T07:20:15.360 に答える
2

あなたが使用したメソッドには署名があると思いますschedule(TimerTask task, long delay)。したがって、実際には、唯一の実行の開始時間を遅らせているだけです。

3 秒ごとに実行するようにスケジュールするにschedule(TimerTask task, long delay, long period)は、3 番目のパラメーターを使用して期間間隔を指定するこのメソッドを使用する必要があります。

ここでタイマークラスの定義を参照して、さらに役立つことができます

http://docs.oracle.com/javase/1.4.2/docs/api/java/util/Timer.html

于 2012-07-29T06:13:15.533 に答える