生产者、消费者交替模型

10 篇文章 0 订阅
package com.atguigu.bigdata.juc;

import java.util.concurrent.TimeUnit;

/**
 * @auth tianmin
 * @date 2020-03-02 - 17:04
 * @nodes 生产者消费者模型
 *      1.实现生产者、消费者交替
 *
 *   总结:
 *      1.高内聚,低耦合,线程操作资源类.
 *      2.判断条件---->业务逻辑---->通知
 *      3.防止虚假唤醒
 */
public class ProductConsume {

    public static void main(String[] args) {
        AirCondition air = new AirCondition();
        // 启动2个线程,一个生产,一个消费

        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    //TimeUnit.MILLISECONDS.sleep(100);
                    air.increment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"生产者1").start();

        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    //TimeUnit.MILLISECONDS.sleep(300);
                    air.increment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"生产者2").start();

        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    //TimeUnit.MILLISECONDS.sleep(200);
                    air.decrement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"消费者1").start();

        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    //TimeUnit.MILLISECONDS.sleep(400);
                    air.decrement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"消费者2").start();
    }
}


class AirCondition{
    private int number = 0;
    //生产
    public synchronized void increment() throws InterruptedException {
        // 1 判断
        // 1.1 线程间通信,不能用if  只能用while
        while (number !=  0){
            //线程等待
            this.wait();
        }

        // 2 业务逻辑
        number++;
        System.out.println("生产到了:" + number);

        // 3 通知
        this.notifyAll();
    }

    //消费
    public synchronized void decrement() throws InterruptedException {
        // 1 判断
        // 1.1 线程间通信,不能用if  只能用while
        while (number == 0){
            this.wait();
        }

        // 2 业务逻辑
        number--;
        System.out.println("消费剩下:" + number);

        // 3 通知
        this.notifyAll();
    }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在Linux中,可以使用多线程编程实现生产者消费者模型。具体实现可以使用pthread库中的线程函数和锁机制。 生产者线程的任务是不断地生产数据,并将数据存储在共享的缓冲区中。消费者线程的任务是从缓冲区中取出数据,并进行处理。 为了保证线程安全,需要使用互斥锁来控制对共享缓冲区的访问。当生产者线程往缓冲区中存入数据时,需要先获取互斥锁,完成数据存储操作后再释放锁。同样,当消费者线程从缓冲区中取出数据时也需要获取互斥锁。 当缓冲区满时,生产者线程需要等待消费者线程取走一部分数据后再继续生产。这可以使用条件变量来实现。生产者线程在往缓冲区中存储数据时,如果缓冲区已满,则等待条件变量。当消费者线程取出一部分数据后,会唤醒生产者线程,继续进行生产。 同样,当缓冲区为空时,消费者线程需要等待生产者线程生产数据后再进行消费。这可以使用另一个条件变量来实现。当消费者线程从缓冲区中取出数据时,如果缓冲区为空,则等待条件变量。当生产者线程往缓冲区中存储数据后,会唤醒消费者线程,继续进行消费。 下面是一个简单的Linux线程生产者消费者模型的示例代码: ``` #include <pthread.h> #include <stdio.h> #include <stdlib.h> #define BUFFER_SIZE 10 #define PRODUCER_NUM 3 #define CONSUMER_NUM 2 int buffer[BUFFER_SIZE]; int count = 0; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t buffer_not_empty = PTHREAD_COND_INITIALIZER; pthread_cond_t buffer_not_full = PTHREAD_COND_INITIALIZER; void *producer(void *arg) { int id = *((int*)arg); while (1) { pthread_mutex_lock(&mutex); if (count == BUFFER_SIZE) { pthread_cond_wait(&buffer_not_full, &mutex); } buffer[count++] = id; printf("producer %d produce one item, count=%d\n", id, count); pthread_cond_signal(&buffer_not_empty); pthread_mutex_unlock(&mutex); sleep(1); } return NULL; } void *consumer(void *arg) { int id = *((int*)arg); while (1) { pthread_mutex_lock(&mutex); if (count == 0) { pthread_cond_wait(&buffer_not_empty, &mutex); } int item = buffer[--count]; printf("consumer %d consume one item, count=%d\n", id, count); pthread_cond_signal(&buffer_not_full); pthread_mutex_unlock(&mutex); sleep(1); } return NULL; } int main() { pthread_t producer_threads[PRODUCER_NUM]; pthread_t consumer_threads[CONSUMER_NUM]; int i, rc; int producer_ids[PRODUCER_NUM]; int consumer_ids[CONSUMER_NUM]; for (i = 0; i < PRODUCER_NUM; i++) { producer_ids[i] = i + 1; rc = pthread_create(&producer_threads[i], NULL, producer, &producer_ids[i]); if (rc != 0) { fprintf(stderr, "producer %d create failed\n", i + 1); exit(1); } } for (i = 0; i < CONSUMER_NUM; i++) { consumer_ids[i] = i + 1; rc = pthread_create(&consumer_threads[i], NULL, consumer, &consumer_ids[i]); if (rc != 0) { fprintf(stderr, "consumer %d create failed\n", i + 1); exit(1); } } for (i = 0; i < PRODUCER_NUM; i++) { pthread_join(producer_threads[i], NULL); } for (i = 0; i < CONSUMER_NUM; i++) { pthread_join(consumer_threads[i], NULL); } return 0; } ``` 在上述代码中,生产者线程的数量为3,消费者线程的数量为2,缓冲区大小为10。生产者线程会不断地往缓冲区中存储数据,消费者线程会不断地从缓冲区中取出数据,直到线程被中止。 运行上述代码,可以看到生产者线程和消费者线程交替执行,并正确地实现了生产者消费者模型
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值