菜单

Administrator
Administrator
发布于 2024-10-09 / 11 阅读
0
0

生产者消费者模型的简单实现

用ReentrantLock和condition实现

import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class ProducerAndComsumer{
    //用一个类实现简单的生产者消费者模型
     List<Integer> buffer = new LinkedList<>();
     int maxSize = 10;//缓冲区最大容量
     Lock lock = new ReentrantLock();
     Condition notFull = lock.newCondition();//notFull条件变量,表示缓冲区未满
     Condition notEmpty = lock.newCondition();//notEmpty条件变量,表示缓冲区非空

    Test(int sz){
        maxSize = sz;
    }
    void produce(int value){
        lock.lock();
        try{
            while(buffer.size() == maxSize){
                notFull.await();//等待notFull条件变量,直到缓冲区未满
            }
            buffer.add(value);//在唤醒notEmpty之前,先添加元素
            notEmpty.signal();//不能在finall中调用signal,否则会导致死锁
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally{
            lock.unlock();

        }
    }
    int consume(){
        lock.lock();
        try{
            while(buffer.isEmpty()){
                notEmpty.await();//等待notEmpty条件变量,直到缓冲区非空
            }
            int value = buffer.remove(0);
            notFull.signal();//移出元素后,通知notFull条件变量,表示缓冲区未满
            return value;
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally{
            lock.unlock();
        }
    }

    public static void main(String[] args) {
        Test test = new Test(5);
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                test.produce(i);
                System.out.println("Produced " + i);
            }
        }).start();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                int value = test.consume();
                System.out.println("Consumed " + value);
            }
        }).start();
    }
}


评论