Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package Lab3;
- import java.util.ArrayList;
- import java.util.List;
- import java.util.concurrent.Semaphore;
- public class BarberShop {
- static Semaphore customer=new Semaphore(5);
- static Semaphore barber=new Semaphore(1);
- static int waitingCustomers = 0;
- void customerComesIn() throws InterruptedException {
- // TODO: 3/29/20 Synchronize this method, invoked by a Customer thread
- customer.acquire();
- waitingCustomers++;
- }
- void barber() throws InterruptedException {
- // TODO: 3/29/20 Synchronize this method, invoked by Barber thread
- while(waitingCustomers==0){
- Thread.sleep(1000);
- }
- barber.acquire();
- // Cutting hair....
- System.out.println("Next one please! "+(waitingCustomers--)+" customers left!");
- customer.release();
- barber.release();
- }
- public static void main(String[] args) throws InterruptedException {
- List<Thread>list=new ArrayList<>();
- for(int i=0;i<100;i++){
- list.add(new Barber());
- list.add(new Customer());
- }
- for(Thread t:list){
- t.start();
- }
- for(Thread t:list){
- t.join();
- }
- }
- static class Barber extends Thread{
- BarberShop barber=new BarberShop();
- @Override
- public void run() {
- try {
- barber.barber();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- }
- static class Customer extends Thread{
- BarberShop customer=new BarberShop();
- @Override
- public void run() {
- try {
- customer.customerComesIn();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement