コード スニペットのいくつかのエラー:
- クラスを拡張しますが
Thread
、これはあまり良い習慣ではありません
Timer
内に がありますThread
か? Timer
aは単独で実行されるため、意味がありませんThread
。
むしろ(必要な場合/必要に応じて)実装する必要がありますが、短い例についてはこちらRunnable
を参照してください。Thread
Timer
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 値を表示します (それ自体とタイマーは の後に終了します):counter
Thread
counter
counter==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
}
}