Java Reference
In-Depth Information
How It Works
We've made the
inTray
object a synchronized
LinkedList
, by passing it to the static
synchronizedList()
method in the
Collections
class. This method returns a thread-safe
List
based
on the original
LinkedList
object. We use the thread-safe
List
object to store up to
maxTransactions
transactions - eight in this case. The
doTransaction()
method for a
Clerk
object makes sure that a
transaction is only added to the list if there are less than eight transactions queued.
The
doTransaction()
method for the
Bank
object always obtains the first object in the
List
, so the
transactions will be processed in the sequence in which they were added to the
list
.
If your operating system supports priority scheduling, altering the thread priority values will change the
pattern of servicing of the transactions.
Summary
In this chapter you have learned about threads and how you can create and manage them. We will be
using threads from time to time in examples later in this topic so be sure you don't move on from here
without being comfortable with the basic ideas of how you create and start a thread.
The essential points that we have covered in this chapter are:
Threads are subtasks in a program that can be in execution concurrently.
❑
A thread is represented by an object of the class
Thread
. Execution of a thread begins with
the execution of the
run()
method defined in the class
Thread
.
❑
You define the code to be executed in a thread by implementing the
run()
method in a class
derived from
Thread
, or in a class that implements the interface
Runnable
.
❑
A thread specified as
daemon
will cease execution when the thread that created it ends.
❑
A thread that isn't a daemon thread is called a
user
thread
. A user thread will not be
terminated automatically when the thread that created it ends.
❑
You start execution of a thread by calling the
start()
method for its
Thread
object. If you
need to halt a thread before normal completion you can stop execution of a thread by calling
the
interrupt()
method for its
Thread
object.
❑
Methods can be declared as
synchronized
. Only one
synchronized
instance method for
an object can execute at any given time. Only one
synchronized
static
method for a
class can execute at one time.
❑
A code block can be declared as
synchronized
on an object. Only one synchronized code
block for an object can execute at any given time.
❑
In a synchronized method or code block, you can call the
wait()
method inherited from the
class
Object
to halt execution of a thread. Execution of the waiting thread will continue
when the
notify()
or
notifyAll()
method inherited from
Object
is called by a thread
synchronized on the same object.
❑