Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package Lab3;
- import java.util.*;
- import java.util.concurrent.Semaphore;
- public class Exercise5 {
- static int waitingCustomers = 0;
- static Semaphore availableSeats = new Semaphore(5);
- static Semaphore lock = new Semaphore(1);
- static Semaphore work = new Semaphore(1);
- static Semaphore customerHere = new Semaphore(0);
- static class Customer extends Thread{
- public Customer() {
- }
- void customerComesIn() throws InterruptedException {
- // TODO: 3/29/20 Synchronize this method, invoked by a Customer thread
- availableSeats.acquire();
- lock.acquire();
- customerHere.release();
- System.out.println("Customer coming in...");
- waitingCustomers++;
- lock.release();
- }
- @Override
- public void run() {
- try {
- customerComesIn();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- }
- static class Barber extends Thread{
- public Barber() {
- }
- void barber() throws InterruptedException {
- // TODO: 3/29/20 Synchronize this method, invoked by Barber thread
- work.acquire();
- if (waitingCustomers > 0) {
- while (true)
- {
- customerHere.acquire();
- System.out.println("Haircut...");
- waitingCustomers--;
- availableSeats.release();
- }
- }
- work.release();
- }
- @Override
- public void run() {
- try {
- barber();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- }
- public static void main(String[] args) {
- // TODO: 3/29/20 Synchronize the scenario
- Barber barber = new Barber();
- HashSet<Customer> customers = new HashSet<Customer>();
- for (int i=0; i<10; i++){
- Customer c = new Customer();
- customers.add(c);
- }
- for (Thread t : customers){
- t.start();
- }
- barber.start();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement