美文网首页
Lock Condition 生产消费

Lock Condition 生产消费

作者: B_Crt | 来源:发表于2019-06-11 15:51 被阅读0次

这是concurretn包提供的一个机制。
可以这么理解:Lock对用锁,condition对应notify和wait

public class LockConditionModel1{
  private final Lock BUFFER_LOCK = new ReentrantLock();
  private final Condition BUFFER_COND = BUFFER_LOCK.newCondition();
  private final Queue<Task> buffer = new LinkedList<>();
  private final int cap;
  private final AtomicInteger increTaskNo = new AtomicInteger(0);
  public LockConditionModel1(int cap) {
    this.cap = cap;
  }
  public Runnable newRunnableConsumer() {
    return new ConsumerImpl();
  }
  public Runnable newRunnableProducer() {
    return new ProducerImpl();
  }

  private class ConsumerImpl extends AbstractConsumer {
    @Override
    public void consume() throws InterruptedException {
      BUFFER_LOCK.lockInterruptibly();
      try {
        while (buffer.size() == 0) {
          BUFFER_COND.await();
        }
        Task task = buffer.poll();
        assert task != null;
    
        Thread.sleep(500);
        System.out.println("consume: " + task.no);
        BUFFER_COND.signalAll();
      } finally {
        BUFFER_LOCK.unlock();
      }
    }
  }
  private class ProducerImpl extends AbstractProducer {
    @Override
    public void produce() throws InterruptedException {
      BUFFER_LOCK.lockInterruptibly();
      try {
        while (buffer.size() == cap) {
          BUFFER_COND.await();
        }
        Task task = new Task(increTaskNo.getAndIncrement());
        buffer.offer(task);
        System.out.println("produce: " + task.no);
        BUFFER_COND.signalAll();
      } finally {
        BUFFER_LOCK.unlock();
      }
    }
  }
  public static void main(String[] args) {
    Model model = new LockConditionModel1(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();
    }
  }
}

可以注意到Lock使用的是ReeentrantLock,Condition是从具体的Lock中去获取的。如果需要生意不理解,可以去熟悉ReentrantLock和Condition。

相关文章

网友评论

      本文标题:Lock Condition 生产消费

      本文链接:https://www.haomeiwen.com/subject/vcpqfctx.html