Advertisement
Guest User

Untitled

a guest
Apr 6th, 2020
334
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.87 KB | None | 0 0
  1. package Lab3;
  2.  
  3. import java.util.ArrayList;
  4. import java.util.List;
  5. import java.util.concurrent.Semaphore;
  6.  
  7. public class BarberShop {
  8.     static Semaphore customer=new Semaphore(5);
  9.     static Semaphore barber=new Semaphore(1);
  10.  
  11.     static int waitingCustomers = 0;
  12.  
  13.     void customerComesIn() throws InterruptedException {
  14.         // TODO: 3/29/20 Synchronize this method, invoked by a Customer thread
  15.  
  16.         customer.acquire();
  17.         waitingCustomers++;
  18.  
  19.  
  20.     }
  21.  
  22.     void barber() throws InterruptedException {
  23.         // TODO: 3/29/20 Synchronize this method, invoked by Barber thread
  24.         while(waitingCustomers==0){
  25.             Thread.sleep(1000);
  26.         }
  27.         barber.acquire();
  28.         // Cutting hair....
  29.         System.out.println("Next one please! "+(waitingCustomers--)+" customers left!");
  30.         customer.release();
  31.         barber.release();
  32.     }
  33.  
  34.     public static void main(String[] args) throws InterruptedException {
  35.         List<Thread>list=new ArrayList<>();
  36.         for(int i=0;i<100;i++){
  37.             list.add(new Barber());
  38.             list.add(new Customer());
  39.         }
  40.         for(Thread t:list){
  41.             t.start();
  42.         }
  43.         for(Thread t:list){
  44.             t.join();
  45.         }
  46.     }
  47.     static class Barber extends Thread{
  48.         BarberShop barber=new BarberShop();
  49.  
  50.         @Override
  51.         public void run() {
  52.             try {
  53.                 barber.barber();
  54.             } catch (InterruptedException e) {
  55.                 e.printStackTrace();
  56.             }
  57.         }
  58.     }
  59.     static class Customer extends Thread{
  60.         BarberShop customer=new BarberShop();
  61.  
  62.         @Override
  63.         public void run() {
  64.             try {
  65.                 customer.customerComesIn();
  66.             } catch (InterruptedException e) {
  67.                 e.printStackTrace();
  68.             }
  69.         }
  70.     }
  71. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement