| Refresh | Home EGTry.com

a simple semaphore example of using its aquire and release methods - exclusively use a resource


SemaphoreTest.java

/*
 * Copyright@ 2011 www.egtry.com
 */

package egtry.thread;

import java.util.concurrent.Semaphore;

public class SemaphoreTest {
  private final Semaphore roomOrganizer=new Semaphore(2, true); //true: first come, first serve
  public static void main(String[] args) {
	 SemaphoreTest test=new SemaphoreTest();
	 test.mystart();
	  

  }
  
  public void mystart() {
		 for(int i=0; i<10; i++) {
			 People people=new People();
			 people.start();
		 }
  }
  
  public class People extends Thread {
	  @Override 
	  public void run() {
		  try {
			  roomOrganizer.acquire();
		  } catch (InterruptedException e) {
			  System.out.println("received InterruptedException");
			  return;
		  }
		  System.out.println("Thread "+this.getId()+" starts to use the room");
		  try {
			  sleep(1000);
		  } catch (InterruptedException e) {
			  
		  }
		  System.out.println("Thread "+this.getId()+" leave the room\n");
		  roomOrganizer.release();
	  }
  }
}



Output

Thread 8 starts to use the room
Thread 9 starts to use the room
Thread 8 leave the room

Thread 11 starts to use the room
Thread 9 leave the room

Thread 13 starts to use the room
Thread 11 leave the room

Thread 15 starts to use the room
Thread 13 leave the room

Thread 17 starts to use the room
Thread 15 leave the room

Thread 10 starts to use the room
Thread 17 leave the room

Thread 14 starts to use the room
Thread 10 leave the room

Thread 12 starts to use the room
Thread 14 leave the room

Thread 16 starts to use the room
Thread 12 leave the room

Thread 16 leave the room