Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.concurrent.Semaphore;
- import java.util.Set;
- import java.util.HashSet;
- import java.util.Random;
- class Demonstration {
- public static void main(String[] args) throws Exception {
- BarberShop.runTest();
- }
- }
- class BarberShop {
- private static final Random random = new Random(System.currentTimeMillis());
- private final Semaphore barberWaitingForCustomer = new Semaphore(0);
- private final Semaphore customerWaitingToOcuupySeat = new Semaphore(0);
- private final Semaphore customerWaitingForHairCutToFinish = new Semaphore(0);
- private final Semaphore barberWaitingForCustomerToLeave = new Semaphore(0);
- private final int maxWaitingSeats;
- private int waitingCustomers = 0;
- public static void runTest() throws Exception {
- BarberShop barberShop = new BarberShop(5);
- Thread barber =
- new Thread(
- new Runnable() {
- @Override
- public void run() {
- try {
- barberShop.lifeCycleOfBarber();
- } catch (InterruptedException ie) {
- }
- }
- });
- barber.setName("Barber");
- barber.start();
- Set<Thread> customers = new HashSet<Thread>();
- for (int i = 0; i < 10; i++) {
- Thread customer =
- new Thread(
- () -> {
- try {
- Thread.sleep(random.nextInt(100));
- barberShop.customerArrives();
- } catch (InterruptedException ie) {
- }
- });
- customer.setName("Customer_" + i);
- customers.add(customer);
- }
- for (Thread customer : customers) {
- customer.start();
- }
- for (Thread customer : customers) {
- customer.join();
- }
- barber.join();
- }
- public BarberShop(int maxWaitingSeats) {
- this.maxWaitingSeats = maxWaitingSeats;
- }
- public void customerArrives() throws InterruptedException {
- synchronized (this) {
- if (waitingCustomers == maxWaitingSeats) {
- System.out.println(
- "Not enough space to wait, " + Thread.currentThread().getName() + " is leaving shop.");
- return;
- }
- waitingCustomers++;
- }
- barberWaitingForCustomer.release();
- System.out.println(Thread.currentThread().getName() + " has arrived.");
- customerWaitingToOcuupySeat.acquire();
- System.out.println(Thread.currentThread().getName() + " has started getting hair-cut.");
- synchronized (this) {
- waitingCustomers--;
- }
- customerWaitingForHairCutToFinish.acquire();
- System.out.println(Thread.currentThread().getName() + " has finished getting hair-cut.");
- barberWaitingForCustomerToLeave.release();
- System.out.println(Thread.currentThread().getName() + " has left shop.");
- }
- public void lifeCycleOfBarber() throws InterruptedException {
- while (true) {
- barberWaitingForCustomer.acquire();
- customerWaitingToOcuupySeat.release();
- System.out.println("Started giving hair cut...");
- Thread.sleep(random.nextInt(150));
- System.out.println("Done with hair cut.");
- customerWaitingForHairCutToFinish.release();
- barberWaitingForCustomerToLeave.acquire();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement