Java Reference
In-Depth Information
Q: Then what are the other threads doing?
A: They are still runnable, but they are waiting in a queue for the
thread scheduler (which is really the JVM) to schedule CPU time
for them. For example, suppose that you have two processes and
each process has two threads. If one CPU is available, then only
one of those threads can be executing at a time, and the other
three are waiting.
Q: How long do they wait?
A: Well, to be precise, it depends. The amount of time a thread gets
on the CPU depends on an indeterminate number of factors.
Some platforms (such as Windows 95/NT/XP) use time-slicing ,
meaning that a thread gets a certain amount of CPU time, and
that's it. Other platforms do not time-slice, but instead schedule
threads based on their priority. The thread scheduler for the JVM
uses fixed priority scheduling . This term means that threads are
scheduled based on their priority, with higher-priority threads run-
ning before lower-priority threads. The JVM thread scheduler is
also preemptive , which means that if a higher-priority thread
comes along, it preempts any currently running lower-priority
thread.
Q: So I can create a Java thread, give it a high priority, and it will hog
the CPU until it is finished?
A: Perhaps, but doubtful. Many operating systems take certain mea-
sures to ensure that threads do not hog the CPU, like intentionally
scheduling a lower-priority thread over a higher one. Therefore ,
you should never rely on thread priority as part of your algorithm
logic . If you need one thread to finish before another, do not
assume that this can be accomplished by using priorities. The pur-
pose of thread priorities is only to allow you to denote one task as
more important than another.
Q: Why use threads at all if you do not have control over which one
is running?
A: Well, that's a good question. A good rule of thumb is to not use
multithreading if you can solve the problem at hand without it.
However, in many real-world programming situations, they can't
be avoided. In fact, threads can often make a problem easier to
solve, while improving the performance of the application at the
same time. Therefore, it is important to understand not just how to
write a thread, but how the thread behaves after it starts running.
Search WWH ::




Custom Search