Java Semaphore control synchronization between producer and consumer

Description

Java Semaphore control synchronization between producer and consumer

import java.util.concurrent.Semaphore;

class Queue {
  int n;//from  ww  w. ja v a2s .  c om

  // Start with consumer semaphore unavailable.
  static Semaphore semCon = new Semaphore(0);
  static Semaphore semProd = new Semaphore(1);

  void get() {
    try {
      semCon.acquire();
    } catch (InterruptedException e) {
      System.out.println("InterruptedException caught");
    }

    System.out.println("Got: " + n);
    semProd.release();
  }

  void put(int n) {
    try {
      semProd.acquire();
    } catch (InterruptedException e) {
      System.out.println("InterruptedException caught");
    }

    this.n = n;
    System.out.println("Put: " + n);
    semCon.release();
  }
}

class Producer implements Runnable {
  Queue queue;

  Producer(Queue q) {
    this.queue = q;
    new Thread(this, "Producer").start();
  }

  public void run() {
    for (int i = 0; i < 20; i++)
      queue.put(i);
  }
}

class Consumer implements Runnable {
  Queue queue;

  Consumer(Queue q) {
    this.queue = q;
    new Thread(this, "Consumer").start();
  }

  public void run() {
    for (int i = 0; i < 20; i++)
      queue.get();
  }
}

public class Main {
  public static void main(String args[]) {
    Queue q = new Queue();
    new Consumer(q);
    new Producer(q);
  }
}



PreviousNext

Related