我即将学习 java 线程工具。
我有两门课:
public class Main {
public static void main(String[] arg) throws Exception {
Timer timer = new Timer();
timer.schedule(new ExecuteTimer(Thread.currentThread()), 2000);
try {
Thread.currentThread().join();
} catch (InterruptedException ex) {
System.out.println("timer stopped");
}
System.out.println("try block executed");
}
}
和计时器类:
public class ExecuteTimer extends TimerTask {
public ExecuteTimer(Thread thread) {
creatingThread = thread;
}
private Thread creatingThread;
@Override
public void run() {
System.out.println("I'm executed!");
creatingThread.interrupt();
}
}
当我调试代码时。我有以下输出:
I'm executed!
timer stopped
try block executed
一切似乎都是最终的,除了在我得到上面的输出后应用程序没有退出。 Eclipse 保持在 Debug模式,没有抛出异常。
最佳答案
当你不再需要Timer来运行任务后,你应该调用timer.cancel()
来释放它的线程。
关于java - 所有代码执行后应用程序未终止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6026020/