我一直在撓頭,試圖找出Java定時器的掛起問題。我想知道這裏有人可以幫忙。高度讚賞任何幫助診斷問題。Java定時器掛起問題
我有一個簡單的程序,有三個TimerTask類(A,B和Stopper)。 A和B分別每400ms和500ms反覆運行。定時器任務計劃在2秒內運行以關閉所有內容。計時器按預期啓動,並且run()方法的任務按預期執行。但是,一旦停止任務執行,我希望程序終止,但它只是在打印「所有任務和定時器被取消,退出」後才掛起。我已經使用jstack來診斷問題嘗試,但並沒有什麼明顯的指示什麼,如果有什麼需要發佈/停止/取消等
這裏是我的代碼:
package com.example.experiments;
import java.util.Date;
/**
* A test timer class to check behavior of exit/hang issues
*/
public class TimerTest {
TimerTest(){
}
class TaskA extends java.util.TimerTask {
TaskA(){
}
public void run() {
System.err.println("A.run() called.");
if (!running){
System.err.println("A: calling this.cancel().");
this.cancel();
return;
}
}
public boolean cancel(){
System.err.println("Canceling TaskA");
return super.cancel();
}
}
class TaskB extends java.util.TimerTask {
TaskB(){
}
public void run(){
System.err.println("B.run() called.");
if (!running){
System.err.println("B: calling this.cancel().");
this.cancel();
return;
}
}
public boolean cancel(){
System.err.println("Canceling TaskB");
return super.cancel();
}
}
private void start(){
this.running = true; // Flag to indicate if the server loop should continue running or not
final java.util.Timer timerA = new java.util.Timer();
final TaskA taskA = new TaskA();
timerA.schedule(taskA, 0, 400);
final java.util.Timer timerB = new java.util.Timer();
final TaskB taskB = new TaskB();
timerB.schedule(taskB, 0, 500);
class StopperTask extends java.util.TimerTask {
private java.util.Timer myTimer;
StopperTask(java.util.Timer timer){
myTimer = timer;
}
public void run(){
taskA.cancel();
taskB.cancel();
timerA.cancel();
timerB.cancel();
this.cancel();
myTimer.cancel();
System.err.println("Stopper task completed");
}
}
final java.util.Timer stopperTimer = new java.util.Timer();
final StopperTask stopperTask = new StopperTask(stopperTimer);
stopperTimer.schedule(stopperTask, 2*1000);
/** Register witjh JVM to be notified on when the JVM is about to exit */
java.lang.Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
System.err.println("shutting down...");
running = false;
taskA.cancel();
taskB.cancel();
timerA.cancel();
timerB.cancel();
stopperTask.cancel();
stopperTimer.cancel();
System.err.println("All tasks and timers canceled, exiting");
System.exit(0);
}
});
}
public static void main(String[] args) {
new TimerTest().start();
}
private boolean running = false;
}
只是一個好奇的評論,你爲什麼不導入所有的類,而是用全名引用它們?你顯然有進口的能力。 – skiwi
「一切都按預期進行,但程序只是在Stopper任務執行時掛起」,這句話令人困惑。阻止者任務總是在某個時間點發出(或)? – kosa
添加條件以測試進程是否正在運行,然後取消它。查看它是否掛起。 – Phani