Creating a Bounded Work Queue [5.0] - Java Thread

Java examples for Thread:BlockingQueue

Description

Creating a Bounded Work Queue [5.0]

Demo Code

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

public class Main {

  public void m() {
    // Create a bounded blocking queue of integers
    final int capacity = 10;
    BlockingQueue<Integer> queue = new ArrayBlockingQueue<Integer>(capacity);

    // 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 w w . ja va  2  s.  c o m*/
    }

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

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

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

  BlockingQueue<Integer> q;

  Worker(BlockingQueue<Integer> q) {
    this.q = q;
  }

  public void run() {
    try {
      while (true) {
        // Retrieve an integer; block if the queue is empty
        Integer x = q.take();

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

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

Related Tutorials