Implementing an Unbounded Work Queue - Java Thread

Java examples for Thread:BlockingQueue

Description

Implementing an Unbounded Work Queue

Demo Code

import java.util.LinkedList;

public class Main {
  public static void main(String[] argv) throws Exception {
    // Create the work queue
    WorkQueue queue = new WorkQueue();

    // Create a set of worker threads
    final int numWorkers = 2;
    Worker[] workers = new Worker[numWorkers];
    for (int i = 0; i < workers.length; i++) {
      workers[i] = new Worker(queue);
      workers[i].start();/*  w ww  . java2s  .c o  m*/
    }

    for (int i = 0; i < 100; i++) {
      queue.addWork(i);
    }

    // Add special end-of-stream markers to terminate the workers
    for (int i = 0; i < workers.length; i++) {
      queue.addWork(Worker.NO_MORE_WORK);
    }
  }
}

class WorkQueue {
  LinkedList queue = new LinkedList();

  // Add work to the work queue
  public synchronized void addWork(Object o) {
    queue.addLast(o);
    notify();
  }

  // Retrieve work from the work queue; block if the queue is empty
  public synchronized Object getWork() throws InterruptedException {
    while (queue.isEmpty()) {
      wait();
    }
    return queue.removeFirst();
  }
}

class Worker extends Thread {
  static final Object NO_MORE_WORK = new Object();

  WorkQueue q;

  Worker(WorkQueue q) {
    this.q = q;
  }

  public void run() {
    try {
      while (true) {
        // Retrieve some work; block if the queue is empty
        Object x = q.getWork();

        // Terminate if the end-of-stream marker was retrieved
        if (x == NO_MORE_WORK) {
          break;
        }

        // Compute the square of x
        int y = ((Integer) x).intValue() * ((Integer) x).intValue();
      }
    } catch (InterruptedException e) {
    }
  }
}

Related Tutorials