Java Reference
In-Depth Information
Managing Threads
In both the examples we've seen in this chapter, the threads are launched and then left to compete for
computer resources. Because all three threads compete in an uncontrolled way for the processor, the
output from the threads gets muddled. This isn't normally a desirable feature in a program. In most
instances where you use threads, the way in which they execute will need to be managed so that they
don't interfere with each other.
Of course, in our examples, the programs are deliberately constructed to release control of the
processor part way through outputting a name. While this is very artificial, similar situations can arise in
practice, particularly where threads are involved in a repetitive operation. It is important to appreciate
that a thread can be interrupted while a source statement is executing. For instance, imagine that a bank
teller is crediting a check to an account and at the same time the customer with that account is
withdrawing some cash through an ATM machine. This might happen in the following way:
The bank teller checks the balance of the customer's account, which is $500.
The ATM machine asks for the account balance.
The teller adds the value of the check, $100, to the account balance to give a figure of $600.
The ATM machine takes $50 off the balance of $500, which gives a figure of $450, and spits
out 5 $10 bills.
The teller assigns the value of $600 to the account balance.
The ATM machine assigns the value $450 to the account balance.
Here you can see the problem very well. Asking the account for its balance and assigning a new balance
to the account are two different operations. As long as this is the case, we can never guarantee that this
type of problem will not occur.
Where two or more threads share a common resource, such as a file or a block of memory, you'll need
to take steps to ensure that one thread doesn't modify a resource while that resource is still being used
by another thread. Having one thread update a record in a file while another thread is part way through
retrieving the same record is a recipe for disaster. One way of managing this sort of situation is to use
synchronization for the threads involved.
Synchronization
The objective of synchronization is to ensure that, when several threads want access to a single resource,
only one thread can access it at any given time. There are two ways in which you can use
synchronization to manage your threads of execution:
You can manage code at the method level - this involves synchronizing methods.
You can manage code at the block level - using synchronizing blocks.
We'll look at how we can use synchronized methods first.
Search WWH ::




Custom Search