Creating a Bounded Work Queue - Java Thread

Java examples for Thread:BlockingQueue

Description

Creating a Bounded Work Queue

Demo Code


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

public class Main {
  public static void main(String[] argv) {
    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 . j av a2  s.  c om*/
    }

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

      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) {
        Integer x = q.take();

        if (x == NO_MORE_WORK) {
          break;
        }

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

Related Tutorials