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 after 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.