A queue(LinkedList) is used to coordinate work between a producer and a set of worker threads. : Producer and consumer « Thread « Java Tutorial






import java.util.LinkedList;

public class Main {
  public static void main(String[] argv) {
    WorkQueue queue = new WorkQueue();

    int numWorkers = 2;
    Worker[] workers = new Worker[numWorkers];
    for (int i = 0; i < workers.length; i++) {
      workers[i] = new Worker(queue);
      workers[i].start();
    }

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

class WorkQueue {
  LinkedList<Object> queue = new LinkedList<Object>();

  public synchronized void addWork(Object o) {
    queue.addLast(o);
    notify();
  }

  public synchronized Object getWork() throws InterruptedException {
    while (queue.isEmpty()) {
      wait();
    }
    return queue.removeFirst();
  }
}

class Worker extends Thread {
  WorkQueue q;

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

  public void run() {
    try {
      while (true) {
        Object x = q.getWork();

        if (x == null) {
          break;
        }
        System.out.println(x);
      }
    } catch (InterruptedException e) {
    }
  }
}








10.13.Producer and consumer
10.13.1.Producer and comsumer with DataInputStream and DataOutputStream
10.13.2.Producer and consumer based on ReadableByteChannel and WritableByteChannel
10.13.3.Producer, consumer and Queue
10.13.4.Synchronized Queue with Producer and Consumer
10.13.5.A queue(LinkedList) is used to coordinate work between a producer and a set of worker threads.