Java 所有代码执行后应用程序未终止
我将学习java线程工具 我有两门课:Java 所有代码执行后应用程序未终止,java,multithreading,wait,Java,Multithreading,Wait,我将学习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.current
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仍处于调试模式,并且未引发异常。在不再需要计时器来运行任务后,应调用
Timer.cancel()
来释放其线程。在不再需要计时器来运行任务后,应调用Timer.cancel()
来释放其线程。使用thread.setDaemon(true)
告诉JVM使线程成为守护进程线程守护进程线程不会阻止程序退出。使用thread.setDaemon(true)
告诉JVM将线程设置为守护进程线程守护进程线程不会阻止程序退出。Thread.currentThread().join()代码>-您是否只是加入了当前线程,而实际上它什么都不做?您需要访问由timer.schedule
@mellamokb创建的线程。我将加入当前线程。并用另一个线程中断当前线程(它具有对当前线程的引用)。有什么问题吗?Thread.currentThread().join()代码>-您是否只是加入了当前线程,而实际上它什么都不做?您需要访问由timer.schedule
@mellamokb创建的线程。我将加入当前线程。并用另一个线程中断当前线程(它具有对当前线程的引用)。有什么问题吗?谢谢你,泰德。我在catch块之后调用了cancel方法。但该程序仍在运行。奇怪,再次谢谢。很抱歉,我调用了TimerTask对象上的cancel方法。我刚刚尝试了Timer对象的cancel方法。很好,谢谢你,泰德。我在catch块之后调用了cancel方法。但该程序仍在运行。奇怪,再次谢谢。很抱歉,我调用了TimerTask对象上的cancel方法。我刚刚尝试了Timer对象的cancel方法。它工作得很好。虽然这在技术上是可行的,但这是对预期的守护进程线程功能的一种黑客攻击,以掩盖真正的问题。如果线程中发生了任何重要的事情,那么当程序退出时它就会死掉-不会进行清理,比如释放资源句柄。虽然这在技术上可能会起作用,但这是对预期守护进程线程功能的黑客攻击,以掩盖真正的问题。如果线程中发生了任何重要的事情,那么当程序退出时它就会死掉——不会进行清理,比如释放资源句柄。