Java Reference
In-Depth Information
You can use the
join()
method to force one thread to wait for another thread to finish. For
example, suppose you modify the code in lines 53-57 in Listing 30.1 as follows:
join()
public void
run() {
Thread thread4 =
Thread
print100
Thread
thread4
new
Thread(
new
PrintChar(
'c', 40
));
thread4.start();
try
{
for
(
int
i =
1
; i <= lastNum; i++) {
System.out.print (
""
+ i);
if
(i ==
50
) thread4.join();
}
thread4.join()
thread4
to finish
Wait for
}
catch
(InterruptedException ex) {
}
thread4
finished
}
A new
thread4
is created and it prints character
c
40 times. The numbers from
50
to
100
are printed after thread
thread4
is finished.
Java assigns every thread a priority. By default, a thread inherits the priority of the
thread that spawned it. You can increase or decrease the priority of any thread by using the
setPriority
method, and you can get the thread's priority by using the
getPriority
method. Priorities are numbers ranging from
1
to
10
. The
Thread
class has the
int
constants
MIN_PRIORITY
,
NORM_PRIORITY
, and
MAX_PRIORITY
, representing
1
,
5
, and
10
, respec-
tively. The priority of the main thread is
Thread.NORM_PRIORITY
.
The JVM always picks the currently runnable thread with the highest priority. A lower-
priority thread can run only when no higher-priority threads are running. If all runnable
threads have equal priorities, each is assigned an equal portion of the CPU time in a circular
queue. This is called
round-robin scheduling
. For example, suppose you insert the following
code in line 16 in Listing 30.1:
setPriority(int)
round-robin scheduling
thread3.setPriority(Thread.MAX_PRIORITY);
The thread for the
print100
task will be finished first.
Tip
The priority numbers may be changed in a future version of Java. To minimize the impact
of any changes, use the constants in the
Thread
class to specify thread priorities.
Tip
A thread may never get a chance to run if there is always a higher-priority thread run-
ning or a same-priority thread that never yields. This situation is known as
contention
or
starvation
. To avoid contention, the thread with higher priority must periodically
invoke the
sleep
or
yield
method to give a thread with a lower or the same priority
a chance to run.
contention or starvation
30.6
✓
✓
Which of the following methods are instance methods in
java.lang.Thread
?
Which method may throw an
InterruptedException
? Which of them are depre-
cated in Java?
run
,
start
,
stop
,
suspend
,
resume
,
sleep
,
interrupt
,
yield
,
join
Check
Point
30.7
If a loop contains a method that throws an
InterruptedException
, why should
the loop be placed inside a
try-catch
block?
30.8
How do you set a priority for a thread? What is the default priority?
Search WWH ::
Custom Search