Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.ArrayList;
- import java.util.List;
- import java.util.concurrent.Semaphore;
- public class BarberShop {
- static int waitingCustomers = 0;
- static Semaphore berber = new Semaphore(0);
- static Semaphore client = new Semaphore(5);
- static Semaphore lock = new Semaphore(1);
- static class Barber extends Thread{
- BarberShop barberShop;
- public Barber (BarberShop barberShop){
- this.barberShop= barberShop;
- }
- public void execute() throws InterruptedException {
- berber.acquire();
- lock.acquire();
- waitingCustomers--;
- barberShop.barber();
- if (waitingCustomers == 0){
- client.release(5);
- }
- lock.release();
- }
- @Override
- public void run() {
- for (int i=0;i<100; i++)
- try {
- execute();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- }
- static class Costumer extends Thread{
- BarberShop barberShop;
- public Costumer (BarberShop barberShop){
- this.barberShop= barberShop;
- }
- public void execute() throws InterruptedException {
- client.acquire();
- lock.acquire();
- waitingCustomers++;
- barberShop.customerComesIn();
- if(waitingCustomers==5){
- berber.release(5);
- }
- lock.release();
- }
- @Override
- public void run() {
- for (int i = 0; i < 1; i++) {
- try {
- execute();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- }
- }
- void customerComesIn() throws InterruptedException {
- // TODO: 3/29/20 Synchronize this method, invoked by a Customer thread
- System.out.println("Costumer comes in");
- }
- void barber() throws InterruptedException {
- // TODO: 3/29/20 Synchronize this method, invoked by Barber thread
- System.out.println("Barber working");
- }
- public static void main(String[] args) throws InterruptedException {
- // TODO: 3/29/20 Synchronize the scenario
- BarberShop barberShop = new BarberShop();
- Barber b = new Barber(barberShop);
- List<Costumer> costumers =new ArrayList<>();
- for (int i=0 ; i<100 ; i++){
- costumers.add(new Costumer(barberShop));
- }
- b.start();
- for (Costumer c :costumers){
- c.start();
- }
- b.join();
- for (Costumer c :costumers){
- c.join(5);
- }
- System.out.println("Uspeshna sinhronizacija");
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement