Stopping a Timer Thread

As we have seen, timer tasks will run forever if you don't shut down the thread. So there are a few different ways we can stop a timer task that's running.

1.
Unplug the machine.
2.
Call System.exit(0), which shuts down all of the threads in an app.
3.
Create the timer as a daemon thread. Doing so will automatically stop the thread once there are only daemon threads left executing, and not user threads. See the “Creating a TimerTask as a Daemon” section later.
4.
After all of the tasks have finished executing, remove all of the references to the Timer object. This is not a great way to do this if you need specific control over the cessation of this task, because when it is garbage collected, the thread terminates. But you ...

Get Java Garage now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.