wait notify 生产消费

wait notify 是Object提供的一个机制。
简单理解就是:他们是配合synchronized来使用的。synchronized获取锁,wait释放并等待锁,notify通知其他等待锁的线程,锁已释放
BlockingQueue已经写过生产消费的抽象。那么我们直接写具体的模型实现就可以了。

public class WaitNotifyModel{
  private final Object BUFFER_LOCK = new Object();
  private final Queue buffer = new LinkedList<>();
  private final int cap;
  private final AtomicInteger increTaskNo = new AtomicInteger(0);
  public WaitNotifyModel(int cap) {
    this.cap = cap;
  }
  public Runnable newRunnableConsumer() {
    return new ConsumerImpl();
  }
  public Runnable newRunnableProducer() {
    return new ProducerImpl();
  }

  private class ConsumerImpl {
    @Override
    public void consume() throws InterruptedException {
      synchronized (BUFFER_LOCK) {
        while (buffer.size() == 0) {
          BUFFER_LOCK.wait();
        }
        Task task = buffer.poll();
        assert task != null;
        Thread.sleep(500);
        System.out.println("consume: " + task.no);
        BUFFER_LOCK.notifyAll();
      }
    }
  }
  private class ProducerImpl {
    @Override
    public void produce() throws InterruptedException {
      synchronized (BUFFER_LOCK) {
        while (buffer.size() == cap) {
          BUFFER_LOCK.wait();
        }
        Task task = new Task(increTaskNo.getAndIncrement());
        buffer.offer(task);
        System.out.println("produce: " + task.no);
        BUFFER_LOCK.notifyAll();
      }
    }
  }
  public static void main(String[] args) {
    Model model = new WaitNotifyModel(3);
    for (int i = 0; i < 5; i++) {
      new Thread(model.newRunnableConsumer()).start();
    }
    for (int i = 0; i < 5; i++) {
      new Thread(model.newRunnableProducer()).start();
    }
  }
}

更好的理解,可以去熟悉synchronized、wait、notifyAll

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