Java Reference
In-Depth Information
Exercises
23.5
(True or False)
State whether each of the following is
true
or
false
. If
false
, explain why.
a) Method
sleep
does not consume processor time while a thread sleeps.
b) Swing components are thread safe.
c)
(Advanced)
Declaring a method
synchronized
guarantees that deadlock cannot occur.
d)
(Advanced)
Once a
ReentrantLock
has been obtained by a thread, the
ReentrantLock
object will not allow another thread to obtain the lock until the first thread releases it.
23.6
(Multithreading Terms)
Define each of the following terms.
a) thread
b) multithreading
c)
runnable
state
d)
timed waiting
state
e) preemptive scheduling
f)
Runnable
interface
g) producer/consumer relationship
h) quantum
23.7
(Advanced: Multithreading Terms)
Discuss each of the following terms in the context of
Java's threading mechanisms:
a)
synchronized
b)
wait
c)
notify
d)
notifyAll
e)
Lock
f)
Condition
23.8
(Blocked State)
List the reasons for entering the
blocked
state. For each of these, describe
how the program will normally leave the
blocked
state and enter the
runnable
state.
23.9
(Deadlock and Indefinite Postponement)
Two problems that can occur in systems that al-
low threads to wait are deadlock, in which one or more threads will wait forever for an event that
cannot occur, and indefinite postponement, in which one or more threads will be delayed for some
unpredictably long time. Give an example of how each of these problems can occur in multithread-
ed Java programs.
23.10
(Bouncing Ball)
Write a program that bounces a blue ball inside a
JPanel
. The ball should
begin moving with a
mousePressed
event. When the ball hits the edge of the
JPanel
, it should bounce
off the edge and continue in the opposite direction. The ball should be updated using a
Runnable
.
23.11
(Bouncing Balls)
Modify the program in Exercise 23.10 to add a new ball each time the user
clicks the mouse. Provide for a minimum of 20 balls. Randomly choose the color for each new ball.
23.12
(Bouncing Balls with Shadows)
Modify the program in Exercise 23.11 to add shadows. As
a ball moves, draw a solid black oval at the bottom of the
JPanel
. You may consider adding a 3-D
effect by increasing or decreasing the size of each ball when it hits the edge of the
JPanel
.
23.13
(Advanced: Circular Buffer with
Lock
s and
Condition
s)
Reimplement the example in
Section 23.8 using the
Lock
and
Condition
concepts presented in Section 23.9.
23.14
(Bounded Buffer: A Real-World Example)
Describe how a highway off-ramp onto a local
road is a good example of a producer/consumer relationship with a bounded buffer. In particular,
discuss how the designers might choose the size of the off-ramp.