/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package education.jtrainer.javainterviewquestions; import java.util.concurrent.Semaphore; import java.util.Random; /** * * @author Diego Gabriele * * This example is related to a bunch of people waiting in a grocery lane to check out * For the example purpose there are 6 people arriving in the lane in a random time interval between 0 and 10 seconds. */ public class MutexTutorial { // max 1 people for 1 cashier static Semaphore semaphore = new Semaphore(1); static class MyBuyer extends Thread { String name = ""; MyBuyer(String name) { this.name = name; } public void run() { try { System.out.println(name + " : trying to pay groceries..."); System.out.println(name + " : available cashiers: " + semaphore.availablePermits()); semaphore.acquire(); System.out.println(name + " : got the permit to pay my goods!"); try { for (int i = 1; i <= 5; i++) { System.out.println(name + " : is paying good n. " + i + ", available cashiers : "+ semaphore.availablePermits()); // assuming it takes 5 sec to pay 1 good Thread.sleep(5000); } } finally { // calling release() after succesfully paying grocery System.out.println(name + " : releasing lock..."); semaphore.release(); System.out.println(name + " : available cashiers now: " + semaphore.availablePermits()); } } catch (InterruptedException e) { e.printStackTrace(); } } } public static void main(String[] args) throws InterruptedException { System.out.println("This is the Mutex tutorial"); MyBuyer t1 = new MyBuyer("Anna"); t1.start(); Thread.sleep(new Random().nextInt(10000)); MyBuyer t2 = new MyBuyer("Bob"); t2.start(); Thread.sleep(new Random().nextInt(10000)); MyBuyer t3 = new MyBuyer("Charlie"); t3.start(); Thread.sleep(new Random().nextInt(10000)); MyBuyer t4 = new MyBuyer("Don"); t4.start(); Thread.sleep(new Random().nextInt(10000)); MyBuyer t5 = new MyBuyer("Eric"); t5.start(); Thread.sleep(new Random().nextInt(10000)); MyBuyer t6 = new MyBuyer("Fred"); t6.start(); } }