Threads and Concurrent Programming
14.6 CASE STUDY: Cooperating Threads
The Customer Class
A Customer thread should model the behavior of taking a number from the TakeANumber gadget. For the sake of this simulation, let’s suppose that after taking a number, the Customer object just prints it out. This will serve as a simple
model of “waiting on line.” What about the Customer’s
state? To help distinguish one customer from another, let’s give each customer a unique ID number starting at 10001, which will be set in the constructor method. Also, as we noted earlier, each Customer needs a reference to the TakeANumber object,
which is passed as a constructor parameter (Fig. 14.20). This
leads to the definition of Customer shown in Figure 14.21. Note that before taking a number the customer sleeps for a random interval of up to 1,000 milliseconds. This will introduce a bit of randomness into the simulation.
Another important feature of this definition is the use of the static
variable number to assign each customer a unique ID number. Remember that a static variable belongs to the class itself, not to its instances.
Therefore, each Customer that is created can share this variable. By
incrementing it and assigning its new value as the Customer’s ID, we
guarantee that each customer has a unique ID number.