Perform the following steps to implement the example:
- Create a class named Task that implements the Runnable interface:
public class Task implements Runnable {
- Declare a private Semaphore attribute named semaphore:
private final Semaphore semaphore;
- Implement the constructor of the class to initialize its attribute:
public Task(Semaphore semaphore){
this.semaphore=semaphore;
}
- Implement the run() method. First, acquire permit for the semaphore attribute writing a message in the console to indicate that circumstance:
@Override
public void run() {
try {
semaphore.acquire();
System.out.printf("%s: Get the semaphore. ",
Thread.currentThread().getName());
- Then, put the thread to sleep for two seconds using the sleep() method. Finally, release the permit and write a message in the console to indicate that circumstance:
TimeUnit.SECONDS.sleep(2);
System.out.println(Thread.currentThread().getName()+":
Release the semaphore.");
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
semaphore.release();
}
- Implement the main class of the example. Create a class named Main with a main() method:
public class Main {
public static void main(String[] args) throws Exception {
- Create a Semaphore object named semaphore with three permits:
Semaphore semaphore=new Semaphore(3);
- Create an array to store 10 Thread objects:
Thread threads[]=new Thread[10];
- Create and start 10 Thread objects to execute 10 Task objects. After starting a thread, put the thread to sleep for 200 milliseconds and call the showLog() method to write information about the Semaphore class:
for (int i=0; i<threads.length; i++) {
Task task=new Task(semaphore);
threads[i]=new Thread(task);
threads[i].start();
TimeUnit.MILLISECONDS.sleep(200);
showLog(semaphore);
}
- Implement a loop with five steps to call the showLog() method to write information about the semaphore and put the thread to sleep for 1 second:
for (int i=0; i<5; i++) {
showLog(semaphore);
TimeUnit.SECONDS.sleep(1);
}
}
- Implement the showLog() method. It receives a Semaphore object as parameter. Write in the console information about the available permits, queued threads, and permits of the semaphore:
private static void showLog(Semaphore semaphore) {
System.out.printf("******************** ");
System.out.printf("Main: Semaphore Log ");
System.out.printf("Main: Semaphore: Avalaible Permits: %d ",
semaphore.availablePermits());
System.out.printf("Main: Semaphore: Queued Threads: %s ",
semaphore.hasQueuedThreads());
System.out.printf("Main: Semaphore: Queue Length: %d ",
semaphore.getQueueLength());
System.out.printf("Main: Semaphore: Fairness: %s ",
semaphore.isFair());
System.out.printf("******************** ");
}