Java Reference
In-Depth Information
A Timer object is used to create threads that execute on a schedule. Note
that the Timer object itself runs in a background thread that executes all
the tasks of the timer. This Timer thread sequentially invokes the
scheduled tasks at their appropriate time, so a task should not take too
long to execute. If it does, other scheduled tasks may be bunching up
waiting for their turn to be scheduled. Therefore, if you have a task that
could possibly take a long time to execute, this task should use its own
Timer object.
The thread for a Timer is non-daemon by default. To make a Timer thread
a daemon thread, you must use the following Timer constructor:
public Timer(boolean isDaemon)
A Timer thread marked as daemon will not keep the application alive,
which is useful for timers that schedule maintenance tasks such as
garbage collection.
A Timer thread can be stopped by invoking the cancel() method of the
Timer class. The cancel() method cancels any scheduled tasks. The
currently running task will complete, but no other tasks can be scheduled
on the timer.
Multithreading Issues
I have discussed three ways to create a thread, and at this point in the topic, I
need to point out that I have shown you just enough about threads to be dan-
gerous! Creating and starting a thread is the easy part. The hard part is making
sure that your threads behave in a manner that maintains the integrity of your
program and the data involved. Keep in mind that the threads in a program
are in the same process memory, and therefore have access to the same
memory.
Because you do not have control over when a thread is scheduled, you never
know when the thread will stop running and have to go back in the priority
queues. The thread might have been in the middle of a data-sensitive task, and
the currently running thread can mess things up while the other thread is wait-
ing to run.
It is not difficult to come up with an example to demonstrate how two
threads can make the data in a program invalid. Take the following BankAc-
count class, which represents a simple bank account with a number, balance,
and methods for making deposits and withdrawals:
Search WWH ::




Custom Search