You are on page 1of 1

Homework 5 CS 431

Winter 2006
Craig A. Rich
The Sleeping Barber Problem
A barbershop consists of a waiting room with s seats and a barber room with one barber chair.
There are c customers and one barber. Customers alternate between growing hair and getting a
haircut. The barber sleeps and cuts hair. If there are no customers to be served, the barber sleeps.
If a customer wants a haircut and all chairs are occupied, then the customer leaves the shop and
skips the haircut. If chairs are available but the barber is busy, then the customer waits in one of the
available chairs until the barber is free. If the barber is asleep, the customer wakes up the barber.

1 Write a Java program that solves the Sleeping Barber Problem using semaphores, synchro-
nizing the barber and customers according to the given rules. The barber and each of the
customers should run as concurrent asynchronous threads that loop forever. The length of
time a customer spends growing hair and the length of time the customer’s haircut takes
should be random numbers of milliseconds chosen by the customer, between 1 and an
upper bound. Use the Semaphore class and its subclasses BinarySemaphore and Count-
ingSemaphore shown in class; they are available on the course web site.
The main program that starts the barber and customer threads should run from the command
line with the following optional arguments:
-s seats
The number of seats in the waiting room, default 5.
-c customers
The number of customers, default 10.
-g growing
The upper bound (in ms) on the time spent growing hair, default 3000.
-h haircut
The upper bound (in ms) on the time spent getting a haircut, default 1000.
-r run
The time (in ms) that the main program runs before exiting, default 60000.
For example,
% java SleepingBarber -s 3 -c 15
2 Turn in the source code for all classes implemented, and the sample output from three runs
of the program using different arguments. A customer should be specifically identified and
print a time stamp and message when he/she 1) starts growing hair, 2) takes a seat in the
waiting room or skips a haircut, and 3) begins a haircut. The barber should print a time
stamp and message when he/she 1) begins sleeping, and 2) begins a haircut. Show the
number of occupied seats in the waiting room each time a customer takes one, and show all
waiting times just before waiting (i.e., calls to nap(ms)).

You might also like