16.2. Managing Threads
In all the examples you've seen so far 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, you will need to manage the way in which they execute 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 partway 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 example, 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. This might happen in the following way:
The bank teller checks the balance of the customer's account, which is $500.
The ATM 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 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 assigns the value $450 to the account balance.
Here you can see the problem ...