SemaphoreTutorial

/*
 * 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
 */
public class SemaphoreTutorial{
    
    static Semaphore semaphore=new Semaphore(2);
    
    static class MyBuyer extends Thread {
                
        String name = "";

        MyBuyer(String name) {
            this.name = name;
        }

        public void run() {

            try {
                System.out.println(name + ": trying to pay goods...");
                                 System.out.println(name + ": available cashiers: " + semaphore.availablePermits());
                System.out.println(name + ": there are "+semaphore.getQueueLength() + " people in the lane waiting to pay their goods who precede me");
                                
                                semaphore.acquire();
                                System.out.println(name + ": got the permit to pay my groceries");
                                    try {
                    for (int i = 1; i <= 5; i++) {
                        System.out.println(name + " : I am paying good n." + i + ", available cashiers : "+ semaphore.availablePermits());
                        // sleep 5000 ms - this is the time needded to pay 
                        Thread.sleep(5000);

                    }

                } finally {
                    // calling release() after succesfully paying the groceries
                    System.out.println(name + ": releasing lock..., cashier is available now to serve a new customer");
                    semaphore.release();
                    System.out.println(name + ": available cashiers: " + semaphore.availablePermits());
                }

            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {

        System.out.println("This is the Semaphore 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();
    }
}