O'Reilly logo

Java Garage by Eben Hewitt

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required