Java Reference
In-Depth Information
Starting a Thread Twice Is Not Valid
A new thread cannot be started twice. For example, the following code compiles fi ne:
23. File source = new File(“somedata.txt“);
24. ReadAFile target = new ReadAFile(source);
25. Thread t = new Thread(target);
26. t.start();
27. t.start();
However, the call to
start
on line 27 throws an
IllegalThreadStateException
at
runtime:
Exception in thread “main” java.lang.IllegalThreadStateException
at java.lang.Thread.start(Thread.java:595)
at ReadAFile.main(ReadAFile.java:27)
Keep an eye out for this scenario on the exam.
Runnable Threads
A
runnable thread
is a thread that is either executing or waiting to be scheduled. The JVM
schedules which thread to execute based on the
thread priority
. The priority is an integer
value, and a thread inherits its priority from the thread that started it. Priority can be
changed at any time using the
setPriority
method of the
Thread
class:
public final void setPriority(int p)
Typically you set a thread's priority to be
MIN_PRIORITY
,
NORM_PRIORITY
, or
MAX_PRIORITY
, static fi elds in the
Thread
class. The
setPriority
method throws
an
IllegalArgumentException
if the argument is not between
MIN_PRIORITY
and
MAX_PRIORITY
.
Java programmers should assume the scheduler uses
preemptive scheduling
, meaning
that if a thread is executing and another thread of a higher priority becomes runnable, it
preempts the lower-priority thread, as Figure 5.2 shows. (Preemptive scheduling is not an
absolute guarantee, so your algorithm logic should not rely on it.)
FIGURE 5.2
The JVM scheduler determines which thread to schedule on a CPU.
preempted
runnable
threads
CPU
scheduled
Search WWH ::
Custom Search