BlockingQueue & LinkedBlockingQueue

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

class Producer implements Runnable {
 private final BlockingQueue queue;
 private int size=0;

 Producer(BlockingQueue q) {
  queue = q;
 }

 public void run() {
  try {
   while (true&&size++<=10) {
    queue.put(produce());
   }
  } catch (InterruptedException ex) {
   // ... handle ...
  }
 }

 Object produce() {
  System.out.println("produce...");
  return "something";
 }
}

class Consumer implements Runnable {
 private final BlockingQueue queue;

 Consumer(BlockingQueue q) {
  queue = q;
 }

 public void run() {
  try {
   while (true&&!queue.isEmpty()) {
    consume(queue.take());
   }
  } catch (InterruptedException ex) {
   // ... handle ...
  }
 }

 void consume(Object x) {
  System.out.println("consume...");
 }
}

class Setup {
 public static void main(String[] args) {
  BlockingQueue q = new LinkedBlockingQueue();
  Producer p = new Producer(q);
  Consumer c1 = new Consumer(q);
  Consumer c2 = new Consumer(q);
  new Thread(p).start();
  new Thread(c1).start();
  new Thread(c2).start();
 }
}

你可能感兴趣的:(BlockingQueue & LinkedBlockingQueue)