Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.ArrayList;
- import java.util.concurrent.Semaphore;
- class Customer extends Thread{
- private BarberShop shop;
- public Customer(BarberShop shop) {
- this.shop = shop;
- }
- @Override
- public void run() {
- for(int i=0;i<10;i++){
- try {
- execute();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- }
- public void execute() throws InterruptedException {
- shop.customerComesIn();
- }
- }
- class Barber extends Thread{
- private BarberShop shop;
- public Barber(BarberShop shop) {
- this.shop = shop;
- }
- @Override
- public void run() {
- for(int i=0;i<10;i++){
- try {
- execute();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- }
- public void execute() throws InterruptedException {
- shop.barber();
- }
- }
- class Semaphores{
- public static Semaphore whoCanWait;
- public static Semaphore barberWake;
- public static Semaphore protect;
- }
- public class BarberShop {
- public static void init(){
- Semaphores.whoCanWait = new Semaphore(5); //broj na slobodni mesta za cekanje
- Semaphores.barberWake = new Semaphore(0); //na pocetokot barberot spie
- Semaphores.protect=new Semaphore(1);
- }
- int waitingCustomers = 0;
- void customerComesIn() throws InterruptedException {
- // TODO: 3/29/20 Synchronize this method, invoked by a Customer thread
- Semaphores.protect.acquire();
- if(waitingCustomers==0){
- Semaphores.barberWake.release();
- }
- waitingCustomers++;
- Semaphores.whoCanWait.release();
- Semaphores.protect.release();
- }
- void barber() throws InterruptedException {
- // TODO: 3/29/20 Synchronize this method, invoked by Barber thread
- Semaphores.barberWake.acquire();
- Semaphores.protect.acquire();
- waitingCustomers--;
- if(waitingCustomers!=0) {
- Semaphores.barberWake.release();
- }
- Semaphores.whoCanWait.release();
- Semaphores.protect.release();
- }
- public static void main(String[] args) throws InterruptedException {
- // TODO: 3/29/20 Synchronize the scenario
- ArrayList<Thread> threads=new ArrayList<>();
- BarberShop shop=new BarberShop();
- Barber barber=new Barber(shop);
- init();
- for(int i=0;i<10;i++){
- Customer customer=new Customer(shop);
- threads.add(customer);
- }
- barber.start();
- for(Thread t: threads){
- t.start();
- }
- for(Thread t: threads){
- t.join();
- }
- for(Thread t:threads){
- if(t.isAlive())
- System.out.println("deadlock");
- }
- System.out.println("Uspeshna sinhronizacija");
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement