Open Source Your Knowledge, Become a Contributor

Technology knowledge has to be shared and made accessible for free. Join the movement.

Create Content

The Producer-Consumer Problem - Part II

The consumer class in our simple example consumes a message from the queue and prints it if there's one; otherwise it waits:

class Consumer implements Runnable {
  public void run() {
    while (true) {
      if (Shared.buffer.size() == 0) {
      if (shouldNotifyProducers()) {
  private void consume() {
    System.out.println("Consumed: " + Shared.buffer.remove());
  private boolean shouldNotifyProducers() {
    return Shared.buffer.size() == Shared.MAX_BUFFER_SIZE - 1;
Open Source Your Knowledge: become a Contributor and help others learn. Create New Content