BlockingQueue 生产消费

与BlockingQueue息息相关的一个话题就是:生产者-消费者模型。

  • 生产者持续生产,直道缓冲区满,阻塞
  • 消费者持续消费,直到缓冲区空,阻塞
  • 生产,消费 并发

接下来,我们就要用BlockingQueue去实现生产消费。
分别定义生产,消费接口。请注意定义中的阻塞。

public interface Consumer{
    void consume() throws InterruptedException;
}

public interface Producer{
    void produce() throws InterruptedException;
}

注意生产者,消费者可以并发。可以对接口进行进一步封装

abstract class AbsConsumer implements Consumer, Runnable{
    @Override
    public void run() {
        try{
            consume();
        } catch(InterruptedException e) {
        }
    }
}

abstract class AbstractProducer implements Producer, Runnable {
  @Override
  public void run() {
      try {
        produce();
      } catch (InterruptedException e) {
      }
    }
}

生产者,消费者消费的个体单位是:

public class Task {
public int no;
  public Task(int no) {
    this.no = no;
  }
}

最后,模型就是:

public class BlockingQueueModel {
  private final BlockingQueue queue;
//这里使用AtomicInteger,保证并发的生产的个体的标记唯一
  private final AtomicInteger increTaskNo = new AtomicInteger(0);
  public BlockingQueueModel(int cap) {
    this.queue = new LinkedBlockingQueue<>(cap);
  }

  public Runnable newRunnableConsumer() {
    return new ConsumerImpl();
  }
  public Runnable newRunnableProducer() {
    return new ProducerImpl();
  }

  private class ConsumerImpl extends AbstractConsumer {
    @Override
    public void consume() throws InterruptedException {
      Task task = queue.take();
      // 固定时间范围的消费,模拟相对稳定的服务器处理过程
      Thread.sleep(500 + (long) (Math.random() * 500));
      System.out.println("consume: " + task.no);
    }
  }
  private class ProducerImpl extends AbstractProducer implements Producer, Runnable {
    @Override
    public void produce() throws InterruptedException {
      // 不定期生产,模拟随机的用户请求
      Thread.sleep((long) (Math.random() * 1000));
      Task task = new Task(increTaskNo.getAndIncrement());
      System.out.println("produce: " + task.no);
      queue.put(task);
    }
  }
  public static void main(String[] args) {
    Model model = new BlockingQueueModel(3);
    for (int i = 0; i < 2; i++) {
      new Thread(model.newRunnableConsumer()).start();
    }
    for (int i = 0; i < 5; i++) {
      new Thread(model.newRunnableProducer()).start();
    }
  }
}

你可能感兴趣的:(BlockingQueue 生产消费)