Advertisement
Guest User

Untitled

a guest
Apr 9th, 2020
152
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.51 KB | None | 0 0
  1. package Lab3;
  2.  
  3. import java.util.concurrent.Semaphore;
  4.  
  5. public class Exercise5 {
  6.  
  7.     int waitingCustomers = 0;
  8.  
  9.     public Semaphore availableSeats = new Semaphore(5);
  10.     public Semaphore lock = new Semaphore(1);
  11.  
  12.  
  13.     public class Customer extends Thread{
  14.         void customerComesIn() throws InterruptedException {
  15.             // TODO: 3/29/20 Synchronize this method, invoked by a Customer thread
  16.             availableSeats.acquire();
  17.             lock.acquire();
  18.             waitingCustomers++;
  19.             lock.release();
  20.         }
  21.  
  22.         @Override
  23.         public void run() {
  24.             try {
  25.                 customerComesIn();
  26.             } catch (InterruptedException e) {
  27.                 e.printStackTrace();
  28.             }
  29.         }
  30.     }
  31.  
  32.     public class Barber extends Thread{
  33.         void barber() throws InterruptedException {
  34.             // TODO: 3/29/20 Synchronize this method, invoked by Barber thread
  35.             lock.acquire();
  36.             if (waitingCustomers > 0) {
  37.                 System.out.println("Haircut...");
  38.                 waitingCustomers--;
  39.                 availableSeats.release();
  40.             }
  41.             lock.release();
  42.         }
  43.  
  44.         @Override
  45.         public void run() {
  46.             try {
  47.                 barber();
  48.             } catch (InterruptedException e) {
  49.                 e.printStackTrace();
  50.             }
  51.         }
  52.     }
  53.  
  54.  
  55.     public static void main(String[] args) {
  56.         // TODO: 3/29/20 Synchronize the scenario
  57.        
  58.     }
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement