生产者,消费者实现

这种模式满足三点要求:
(1)生产者生产数据到缓冲区中,消费者从缓冲区中取数据。
(2)缓冲区满时,生产者线程阻塞,进入等待状态。这期间消费者一旦取走数据,队列未满,就会唤醒阻塞的生产者。
(3)缓冲区空时,消费者线程阻塞,进入等待状态。这期间生产者一旦往队列中放入数据,就会唤醒阻塞的消费者。
阻塞队列

public class MyBlockingQueue {

    private int maxSize;
    private LinkedList<Integer> queue;

    public MyBlockingQueue(int maxSize, LinkedList<Integer> queue) {
        this.maxSize = maxSize;
        this.queue = queue;
    }

    public synchronized void put() throws Exception {
        while (queue.size()==maxSize){
            System.out.println("队列已满,生产者"+Thread.currentThread().getName()+"进入等待");
            wait();
        }
        Random random = new Random();
        int num = random.nextInt(100);
        System.out.println("队列未满,生产者"+Thread.currentThread().getName()+"生产数据"+num);
        if (queue.size()==0){
            notifyAll();
        }
        queue.add(num);
    }

    public synchronized void take() throws Exception {
        while (queue.size()==0){
            System.out.println("队列为空,消费者"+Thread.currentThread().getName()+"进入等待");
            wait();
        }
        if (queue.size()==maxSize){
            notifyAll();
        }
        System.out.println("队列有数据,消费者"+Thread.currentThread().getName()+"去出数据"+queue.remove());
    }
}

生产者 

public class Producer implements Runnable{

    private MyBlockingQueue myBlockingQueue;

    public Producer(MyBlockingQueue myBlockingQueue) {
        this.myBlockingQueue = myBlockingQueue;
    }

    @Override
    public void run() {
        for (int i = 0; i < 5; i++) {
            try {
                myBlockingQueue.put();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

消费者

public class Customer implements Runnable{

    private MyBlockingQueue myBlockingQueue;

    public Customer(MyBlockingQueue myBlockingQueue) {
        this.myBlockingQueue = myBlockingQueue;
    }

    @Override
    public void run() {
        for (int i = 0; i < 5; i++) {
            try {
                myBlockingQueue.take();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个简单的生产者消费者同步代码实现,使用了条件变量(Condition Variable)来进行线程同步: ```C++ #include <iostream> #include <queue> #include <thread> #include <mutex> #include <condition_variable> using namespace std; queue<int> q; // 全局队列 mutex m; // 互斥锁 condition_variable cv; // 条件变量 int cnt = 0; // 生产者生产的数量 const int MAX_CNT = 10; // 生产者生产的最大数量 void producer() { while (cnt < MAX_CNT) { unique_lock<mutex> lk(m); cv.wait(lk, [](){ return q.size() < 5; }); // 如果队列中元素个数 >= 5,则等待 q.push(cnt); cout << "生产者生产了 " << cnt++ << endl; lk.unlock(); cv.notify_all(); this_thread::sleep_for(chrono::seconds(1)); // 睡眠1秒钟 } } void consumer() { while (true) { unique_lock<mutex> lk(m); cv.wait(lk, [](){ return !q.empty(); }); // 如果队列为空,则等待 int value = q.front(); q.pop(); cout << "消费者消费了 " << value << endl; lk.unlock(); cv.notify_all(); this_thread::sleep_for(chrono::seconds(2)); // 睡眠2秒钟 } } int main() { thread t1(producer); thread t2(consumer); t1.join(); t2.join(); return 0; } ``` 在这个代码中,生产者线程和消费者线程共享一个全局队列 `q`,并且使用了互斥锁 `m` 和条件变量 `cv` 来保证线程安全。其中,互斥锁 `m` 用于保护共享资源(队列 `q`)的访问操作,条件变量 `cv` 用于实现线程之间的等待和唤醒操作。 在生产者线程中,首先获取互斥锁 `m`,然后使用条件变量 `cv` 等待队列中元素个数小于 5 的条件。如果条件不满足,则线程等待并释放互斥锁 `m`,直到被其他线程唤醒。如果条件满足,则生产者将一个元素加入队列 `q` 中,并输出生产信息,最后释放互斥锁 `m` 并唤醒其他线程。 在消费者线程中,首先获取互斥锁 `m`,然后使用条件变量 `cv` 等待队列不为空的条件。如果条件不满足,则线程等待并释放互斥锁 `m`,直到被其他线程唤醒。如果条件满足,则消费者从队列 `q` 中取出一个元素,并输出消费信息,最后释放互斥锁 `m` 并唤醒其他线程。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值