package com.tutego.insel.thread.concurrent;

import java.util.concurrent.Semaphore;

public class SemaphoreDemo
{
//  static Semaphore semaphore = new Semaphore( 2 );
  static Semaphore semaphore = new Semaphore( 2, true );

  static Runnable r = new Runnable() {
    public void run() {
      while ( true ) {
        try
        {
          semaphore.acquire();

          System.out.println( "Thread=" + Thread.currentThread().getName() +
                              ", Available Permits=" + semaphore.availablePermits() );
          Thread.sleep( 2000 );
        }
        catch ( InterruptedException e ) {
          e.printStackTrace();
        }
        finally {
          semaphore.release();
        }
      }
    }
  };

  public static void main( String[] args )
  {
    new Thread( r ).start();
    new Thread( r ).start();
    new Thread( r ).start();
  }
}
