The barbershop, sometimes called the sleeping barber, models a barbershop with one barber, one barber's chair, and a waiting room with several chairs. The alternative name of the problem comes from the fact that if there is no one waiting for a haircut, the barber flops in his chair and falls asleep.
Also involved are a number of shaggy-haired customers. A customer entering the barbershop looks around and assesses the situation. If all the waiting room chairs are occupied, the customer leaves the shop to return again at a time when hopefully the queue will be shorter. If there is an open chair the customer sits down and waits for the barber.
Once the barber has finished cutting a customer's hair, the customer leaves the shop which allows another customer to enter the shop (if all the chairs had been occupied) and the the next customer (if there is one) in the queue to get a haircut.
In this example, even after getting their hair cut, the customers come back to the shop until they have had their hair cut some prescribed number of times.
The example contains classes that model the barber (
BARBER), the customers (
CUSTOMER), and the shop with its waiting area (
SHOP). The root class creates as separate objects the barber, the shop, and the set of customers. As each customer is created, it is launched on its lifecycle of getting haircut after haircut until haircuts are no longer needed.
SHOP includes features
leave. Customers call the
enter feature to find out if there is a chair available in the shop. Customers call
leave, after their hair has been cut. Both of these calls are "wrapped" as separate calls in the class
A typical customer lives in this way: As long as he still needs haircuts, he repeatedly does the following steps: He tries to enter the shop. If he's unsuccessful because all the chairs are occupied, he goes off for a while (in the implementation, his processor sleeps and then comes to the end of this step). If he is able to enter the shop, then he puts himself in the queue for a haircut. Once his haircut is complete, he reduces his number of haircuts needed by one, and leaves the shop.