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 {
- String ID;
- public Customer(String ID) {
- this.ID = ID;
- }
- void customerComesIn() throws InterruptedException {
- // TODO: 3/29/20 Synchronize this method, invoked by a Customer thread
- lock.acquire();
- if (waitingCustomers == 5) {
- System.out.println("No free seats for customer" + ID);
- lock.release();
- }
- else {
- System.out.println("Customer " + ID + " coming in...");
- waitingCustomers++;
- lock.release();
- availableSeats.acquire();
- customerHere.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
- while (true) {
- customerHere.acquire();
- work.acquire();
- System.out.println("Haircut...");
- waitingCustomers--;
- work.release();
- availableSeats.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 < 150; i++) {
- Customer c = new Customer(Integer.toString(i));
- customers.add(c);
- }
- for (Thread t : customers) {
- t.start();
- }
- barber.start();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement