Java Reference
In-Depth Information
Thread-1: 1
Thread-1: 2
Thread-1: 3
The operating system assigns a separate thread to each processor or core so the
threadsexecute
concurrently
(atthesametime).Whenacomputerdoesnothaveenough
processors and/or cores, a thread must wait its turn to use the shared processor/core.
The operating system uses a
scheduler
(
http://en.wikipedia.org/wiki/
Scheduling_(computing)
)todeterminewhenawaitingthreadexecutes.Thefol-
lowing list identifies three different schedulers:
• Linux 2.6 through 2.6.22 uses the O(1) scheduler (
ht-
• Linux 2.6.23 uses the Completely Fair Scheduler (
ht-
• Windows NT-based operating systems (e.g., NT, 2000, XP, Vista, and 7) use
a multilevel feedback queue scheduler (
http://en.wikipedia.org/
Thepreviousoutputfromthecountingthreadsapplicationresultedfromrunningthis
application via Windows XP's
multilevel feedback queue
scheduler. Because of this
scheduler, both threads take turns executing.
Caution
Although this outputindicates that thefirst thread starts executing, never
assumethatthethreadassociatedwiththe
Thread
objectwhose
start()
methodis
calledfirstisthefirstthreadtoexecute.Whilethismightbetrueofsomeschedulers,it
might not be true of others.
A multilevel feedback queue and many other thread schedulers take the concept
of
priority
(thread relative importance) into account. They often combine
preemptive
scheduling
(higherprioritythreads
preempt
—interruptandruninsteadof—lowerprior-
itythreads)with
round robin scheduling
(equalprioritythreadsaregivenequalslicesof
time, which are known as
time slices
, and take turns executing).
Thread
supportspriorityviaits
void setPriority(int priority)
meth-
od (set the priority of this
Thread
object's thread to
priority
, which ranges from
Thread.MIN_PRIORITY
to
Thread.MAX_PRIORITY
—
Thread.NORMAL_PRIORITY
identifies the default
priority) and
int getPriority()
method (return the current priority).