美文网首页
使用ReentrantLock和Condition实现生产者-消

使用ReentrantLock和Condition实现生产者-消

作者: 不积小流_无以成江海 | 来源:发表于2023-05-17 14:56 被阅读0次

使用ReentrantLock和Condition实现生产者-消费者模型的示例代码

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class ProducerConsumer {
    private final ReentrantLock lock = new ReentrantLock();
    private final Condition notFull = lock.newCondition();
    private final Condition notEmpty = lock.newCondition();
    private final Object[] buffer = new Object[10];
    private int count, putIndex, takeIndex;

    public void put(Object item) throws InterruptedException {
        lock.lock();
        try {
            while (count == buffer.length) {
                notFull.await();
            }
            buffer[putIndex] = item;
            if (++putIndex == buffer.length) {
                putIndex = 0;
            }
            count++;
            notEmpty.signal();
        } finally {
            lock.unlock();
        }
    }

    public Object take() throws InterruptedException {
        lock.lock();
        try {
            while (count == 0) {
                notEmpty.await();
            }
            Object item = buffer[takeIndex];
            if (++takeIndex == buffer.length) {
                takeIndex = 0;
            }
            count--;
            notFull.signal();
            return item;
        } finally {
            lock.unlock();
        }
    }
}

使用ReentrantLock来保护共享资源buffer,并使用两个Condition来表示buffer是否已满和是否已空。在put()方法中,如果buffer已满,则调用notFull.await()进入等待状态,直到其他线程调用notEmpty.signal()通知它们buffer已经有空闲位置了。在take()方法中,如果buffer已空,则调用notEmpty.await()进入等待状态,直到其他线程调用notFull.signal()通知它们buffer已经有新的数据了。这样就可以实现生产者-消费者模型的线程同步了。

相关文章

网友评论

      本文标题:使用ReentrantLock和Condition实现生产者-消

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