Java Semaphore class

Introduction

A semaphore controls access to a shared resource through a counter.

Semaphore has the two constructors shown here:

Semaphore(int num)  
Semaphore(int num, boolean how) 

To acquire a permit, call the acquire() method, which has these two forms:

void acquire() throws InterruptedException  
void acquire(int  num) throws InterruptedException 

To release a permit, call release(), which has these two forms:

void release()  
void release(int  num) 

import java.util.concurrent.Semaphore;

public class Main {

  public static void main(String args[]) {
    Semaphore sem = new Semaphore(1);

    new IncrementThread(sem, "A");
    new DecrementThread(sem, "B");

  }/*  ww w . ja v a2  s. c  o  m*/
}

// A shared resource.
class Shared {
  static int count = 0;
}

// A thread of execution that increments count.
class IncrementThread implements Runnable {
  String name;
  Semaphore sem;

  IncrementThread(Semaphore s, String n) {
    sem = s;
    name = n;
    new Thread(this).start();
  }

  public void run() {
    System.out.println("Starting " + name);
    try {
      System.out.println(name + " is waiting for a permit.");
      sem.acquire();
      System.out.println(name + " gets a permit.");
      for (int i = 0; i < 5; i++) {
        Shared.count++;
        System.out.println(name + ": " + Shared.count);
        Thread.sleep(10);
      }
    } catch (InterruptedException exc) {
      System.out.println(exc);
    }

    System.out.println(name + " releases the permit.");
    sem.release();
  }
}

// A thread of execution that decrements count.
class DecrementThread implements Runnable {
  String name;
  Semaphore sem;

  DecrementThread(Semaphore s, String n) {
    sem = s;
    name = n;
    new Thread(this).start();
  }

  public void run() {

    System.out.println("Starting " + name);

    try {
      System.out.println(name + " is waiting for a permit.");
      sem.acquire();
      System.out.println(name + " gets a permit.");
      for (int i = 0; i < 5; i++) {
        Shared.count--;
        System.out.println(name + ": " + Shared.count);
        Thread.sleep(10);
      }
    } catch (InterruptedException exc) {
      System.out.println(exc);
    }

    // Release the permit.
    System.out.println(name + " releases the permit.");
    sem.release();
  }
}



PreviousNext

Related