简单实现生产者消费者问题

    生产者消费者问题,是一个多线程同步问题的经典案例。该问题描述了两个共享固定大小缓冲区的线程--即所谓的“生产者”和“消费者”在实际运行时会发生的问题。。生产者主要的作用是生产一定量的数据放置到缓冲区,然后重复此过程。与此同时,消费者也在缓冲区消耗这些数据。
    该问题的关键就是要保证生产者不会在缓冲区满时加入数据,消费者也不会在缓冲区空时消耗数据。

话不多说,直接上代码

/**
 * 馒头对象
 * @author Quan
 *
 */
public class Cake {          

    private int id;

    public Cake(int id) {
        this.id = id;
    }

    @Override
    public String toString() {
        return " " + id + " Cake";
    }

}
/**
 * 容器对象    用来放馒头
 * @author Quan
 *
 */
public class Frame {

    private volatile int count = 0;    //设置容器的大小,最大只能装10个馒头

    public synchronized void push(Cake cake){      //放入馒头
        try {
            while(count>10){       //如果大于容器的数量,就进行等待
                wait();
            }
            count ++;
            System.out.println("做第" + cake.toString());
            notify();                //通知消费者取馒头
        } catch (Exception e) {
            System.out.println("push error");
        }
    }

    public synchronized void pop(Cake cake){       //取馒头
        try {
            while(count == 0){      //如果馒头数量为0,就进行等待
                wait();
            }
            count --;
            System.out.println("吃第" + cake.toString());
            notify();              //通知生产者做馒头
        } catch (Exception e) {
            System.out.println("pop error");
        }
    }

    public void count(){        
        System.out.println("当前剩余" + count + "个馒头");
    }
}

生产者和消费者都要持有一个容器对象,以对容器中的对象也就是馒头数量进行操作


/**
 * 生产者
 * @author Quan
 *
 */
public class Producer implements Runnable{

    private Frame frame;        //持有容器对象

    private int total;

    public Producer(Frame frame,int i) {
        this.frame = frame;
        this.total = i;
    }

    @Override
    public void run() {
        try {
            for (int i = 0; i < total; i++) {             //做10个馒头
                Cake cake = new Cake(i);
                frame.push(cake);
                Thread.sleep(100);                    //每做一个馒头休眠100毫秒
            }

        } catch (Exception e) {
            System.out.println("Producer Error");
        }
    }
}
/**
 * 消费者
 * @author Quan
 *
 */
public class Consumer implements Runnable{

    private Frame frame;    //持有容器对象

    private int total;

    public Consumer(Frame frame,int i) {
        this.frame = frame;
        this.total = i;
    }

    @Override
    public void run() {
        try {
            for(int i = 0; i < total; i++){
                Cake cake = new Cake(i);
                frame.pop(cake);
                Thread.sleep(200);   //每吃一个馒头,休眠200毫秒
                frame.count();
            }
        } catch (Exception e) {
            System.out.println("Consumer Error");
        }
    }
}
/**
 * 生产者消费者测试主函数
 * @author Quan
 *
 */
/**
 * 生产者消费者测试主函数
 * @author Quan
 *
 */
public class ProductorConsumer {

    public static void main(String[] args) throws Exception {
        Frame frame = new Frame();

        Consumer consumer = new Consumer(frame,5);       //消费6个馒头

        Producer producer = new Producer(frame,6);       //生产5个馒头

        ExecutorService exes = Executors.newCachedThreadPool();

        exes.execute(producer);

        exes.execute(consumer);

        TimeUnit.SECONDS.sleep(5);

        exes.shutdownNow();
    }
}

运行程序结果:
这里写图片描述

修改生产消费馒头的数量:

/**
 * 生产者消费者测试主函数
 * @author Quan
 *
 */
public class ProductorConsumer {

    public static void main(String[] args) throws Exception {
        Frame frame = new Frame();

        Consumer consumer = new Consumer(frame,6);       //消费6个馒头

        Producer producer = new Producer(frame,5);       //生产5个馒头

        ExecutorService exes = Executors.newCachedThreadPool();

        exes.execute(producer);

        exes.execute(consumer);

        TimeUnit.SECONDS.sleep(5);

        exes.shutdownNow();
    }
}

程序运行结果:
这里写图片描述
这里的pop error原因是:在主线程休眠5秒钟后,产生中断信号,消费者在线程在调用pop去取馒头的等待中接到中断信号,退出等待,抛出java.lang.InterruptedException异常,程序退出pop方法,回到消费者的Thread.sleep(200); //每吃一个馒头,休眠200毫秒 位置,依次执,程序正常退出。

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
生产者消费者问题一个经典的并发题,它涉及到多个进程或线程之间的同步和互斥。在C语言中,可以使用线程和信号量来实现生产者消费者问题。 具体实现步骤如下: 1. 定义一个共享的缓冲区,可以使用队列或环形缓冲区。 2. 定义一个生产者线程和一个消费者线程。 3. 在生产者线程中,不断生成随机数并将其添加到缓冲区内,并在此之后将 full 计数器加一。 4. 在消费者线程中,检索当前可用的缓冲区,如果满足条件,则从计数器中减去 1,并从缓冲区中读取数据,并在满足特定条件时输出该数据。 5. 使用信号量来实现同步和互斥,保证在生产者没有向缓冲区提交任何内容时,消费者不会读取缓冲区中的任何数字。 下面是一个简单的C语言实现生产者消费者问题的代码示例: ``` #include <stdio.h> #include <stdlib.h> #include <pthread.h> #include <semaphore.h> #define BUFFER_SIZE 10 int buffer[BUFFER_SIZE]; int in = 0; int out = 0; int count = 0; sem_t empty; sem_t full; pthread_mutex_t mutex; void *producer(void *arg) { int item; while (1) { item = rand() % 100; // 生成随机数 sem_wait(&empty); // 等待空缓冲区 pthread_mutex_lock(&mutex); // 加锁 buffer[in] = item; in = (in + 1) % BUFFER_SIZE; count++; printf("Producer produced item %d\n", item); pthread_mutex_unlock(&mutex); // 解锁 sem_post(&full); // 发送满缓冲区信号 } } void *consumer(void *arg) { int item; while (1) { sem_wait(&full); // 等待满缓冲区 pthread_mutex_lock(&mutex); // 加锁 item = buffer[out]; out = (out + 1) % BUFFER_SIZE; count--; if (item % 2 == 0) { printf("Consumer consumed item %d\n", item); } pthread_mutex_unlock(&mutex); // 解锁 sem_post(&empty); // 发送空缓冲区信号 } } int main() { pthread_t producer_thread, consumer_thread; sem_init(&empty, 0, BUFFER_SIZE); sem_init(&full, 0, 0); pthread_mutex_init(&mutex, NULL); pthread_create(&producer_thread, NULL, producer, NULL); pthread_create(&consumer_thread, NULL, consumer, NULL); pthread_join(producer_thread, NULL); pthread_join(consumer_thread, NULL); sem_destroy(&empty); sem_destroy(&full); pthread_mutex_destroy(&mutex); return 0; } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值