condition 实现生产者和消费者简单示例

synchronized 与 wait()和 notify() 、notifyAll() 方法相结合可以实现等待/通知模式,ReentantLock 同样也可以实现,需要借助 Condition 实现

public class ConditionTest {

    private  Lock lock = new ReentrantLock();
    private  Condition condition = lock.newCondition();
    private volatile Queue<String> queue = new LinkedList<>();

    public void addTask(String s) {
        lock.lock();
        try {
            queue.add(s);
            condition.signalAll();
        } finally {
            lock.unlock();
        }
    }

    public String getTask() throws InterruptedException {
        lock.lock();
        try {
            while (queue.isEmpty()) {
                condition.await();
            }
            return queue.remove();
        } finally {
            lock.unlock();
        }
    }
    
}

 

posted @ 2022-04-04 18:24  纵码万水千山  阅读(53)  评论(0编辑  收藏  举报