This is an old revision of the document!
Another classical problem takes place in a barber shop. This problem is due to Dijkstra. The barber shop has one barber, a barber chair, and n chairs for waiting customers, if any, to sit on. If there are no customers present, the barber sits down in the barber chair and falls asleep. When a customer arrives, he has to wake up the sleeping barber. If additional customers arrive while the barber is cutting a customer's hair, then they sit down (if there are empty chairs) or leave the shop (if all chairs are full). The problem is how to program the barber and the customers without getting into race conditions.
In your solution, you may want to introduce a class Shop
.
A Shop
object has-a Barber
object. A Barber
object is-a Thread
object. The run
method of the
Barber
class should give rise to the output
The barber sits down and falls asleep
and
The barber wakes up
, whenever appropriate. In your
solution, you may also want to introduce a class
Customer
. A Customer
object is-a Thread
.
The run
method of the Customer
class should
give rise to the output Customer i enters
,
Customer i sits down
(if there is an empty
chair), Customer i gets a haircut
(if there
is an empty chair and once it is his turn), and
Customer i leaves
.