开发者

Application not terminated after all code executed

开发者 https://www.devze.com 2023-03-06 04:06 出处:网络
I\'m about to learn the java threading facility. I have 2 classes: public class Main { public static void main(String[] arg) throws Exception {

I'm about to learn the java threading facility.

I have 2 classes:

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");
    }
}

and the timer class:

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();

    }

}

When I debug the code. I have following output:

I'm executed!
timer stopped
try block executed

Everything seems to be final except the app didn't exit afte开发者_如何学运维r I have the output above. The eclipse remain in debug mode and no exception has been thrown.


After you no longer need the Timer to run tasks, you should call timer.cancel() to release its thread.


Use thread.setDaemon(true) to tell the JVM to make the thread a daemon thread. Daemon threads do not prevent the program from exiting.

0

精彩评论

暂无评论...
验证码 换一张
取 消