Advertisement
Guest User

Untitled

a guest
Apr 9th, 2020
171
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.24 KB | None | 0 0
  1. package Lab3;
  2.  
  3. import java.util.*;
  4. import java.util.concurrent.Semaphore;
  5.  
  6. public class Exercise5 {
  7.  
  8.     static int waitingCustomers = 0;
  9.  
  10.     static Semaphore availableSeats = new Semaphore(5);
  11.     static Semaphore lock = new Semaphore(1);
  12.     static Semaphore work = new Semaphore(1);
  13.     static Semaphore customerHere = new Semaphore(0);
  14.  
  15.  
  16.      static class Customer extends Thread{
  17.         public Customer() {
  18.         }
  19.  
  20.         void customerComesIn() throws InterruptedException {
  21.             // TODO: 3/29/20 Synchronize this method, invoked by a Customer thread
  22.             availableSeats.acquire();
  23.             lock.acquire();
  24.             customerHere.release();
  25.             System.out.println("Customer coming in...");
  26.             waitingCustomers++;
  27.             lock.release();
  28.         }
  29.  
  30.         @Override
  31.         public void run() {
  32.             try {
  33.                 customerComesIn();
  34.             } catch (InterruptedException e) {
  35.                 e.printStackTrace();
  36.             }
  37.         }
  38.     }
  39.  
  40.     static class Barber extends Thread{
  41.         public Barber() {
  42.         }
  43.  
  44.         void barber() throws InterruptedException {
  45.             // TODO: 3/29/20 Synchronize this method, invoked by Barber thread
  46.             work.acquire();
  47.             if (waitingCustomers > 0) {
  48.                 while (true)
  49.                 {
  50.                     customerHere.acquire();
  51.                     System.out.println("Haircut...");
  52.                     waitingCustomers--;
  53.                     availableSeats.release();
  54.                 }
  55.             }
  56.             work.release();
  57.         }
  58.  
  59.         @Override
  60.         public void run() {
  61.             try {
  62.                 barber();
  63.             } catch (InterruptedException e) {
  64.                 e.printStackTrace();
  65.             }
  66.         }
  67.     }
  68.  
  69.     public static void main(String[] args) {
  70.         // TODO: 3/29/20 Synchronize the scenario
  71.         Barber barber = new Barber();
  72.         HashSet<Customer> customers = new HashSet<Customer>();
  73.  
  74.         for (int i=0; i<10; i++){
  75.             Customer c = new Customer();
  76.             customers.add(c);
  77.         }
  78.  
  79.         for (Thread t : customers){
  80.             t.start();
  81.         }
  82.  
  83.         barber.start();
  84.     }
  85. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement