生产、消费模型

生产、消费模型:

一、生产、消费模型:

  在线程间通讯的时候,当在一个对象上调用wait()方法时,当前线程就会进入wait状态,直到收到另一个对象的notify()发出通知,才会执行下一部计算,而且线程在wait的时候,也可能被中断,这就是"生产/消费模型"

 

二、简单实现:

 1.生产和消费线程用来操作的对象:

 

package 生产_消费模型;
/**
 * 用来交换的数据对象模型
 * @author Administrator
 *
 */
public class Student {

	int id;
	String name;
	
	public String toString(){
			
		return id+"<>"+name;
	}
	
}

 

 

 2.生产线程:

 

package 生产_消费模型;

import java.util.List;

public class ProduceThread extends Thread {

	//与消费线程或以共同存取的对象列表
	private List shareList;
	
	//用来标记的放入对象的每一个独立的编号
	private static int count;
	
	//构造器参数是生产线程要放入数据的队列
	public ProduceThread(List shareList){
	    this.shareList = shareList;	
	}
	
	
	@Override
	public void run() {
		// TODO Auto-generated method stub
		//super.run();
		System.out.println("生产线程已经启动:"+shareList.size());
		while(true){
			try {
				Thread.sleep(2000);
				
				synchronized (shareList) {
					
					while(shareList.size()>0){
						shareList.wait();
					}
					
					while(shareList.size()==0){
						
						Student st = new Student();
						count++;
						st.id = count;
						st.name="对象"+count;
						
					System.out.println("生产线程放入对象:"+st.toString());	
						
						shareList.add(st);
						shareList.notify();
					}
					
				}
				
				
				
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			

		}
	}
}

 

 

    通过构造函数把操作对象的List传进去,如果List里面有对象,就要wait,而当List里面没有对象,该生产线程就要产生一个,并发出notify的通知.并把操作的对象加入操作对象的List

 

 3.消费线程:

package 生产_消费模型;

import java.util.List;

/**
 * 消费线程
 * @author Administrator
 *
 */

public class CustomerThread extends Thread{

	private List shareList;
	
	
	@Override
	public void run() {
		// TODO Auto-generated method stub
		//super.run();
		System.out.println("消费线程已经启动:"+shareList.size());
		
		while(true){
			
			synchronized (shareList) {
				
				while (shareList.size()==0) {
				//如果没有,消费线程就要等待
					try {
						shareList.wait();
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					
				}
				
				while(shareList.size()>0){
					
					System.out.println("消费线程取出:"+shareList.remove(0).toString());
					
					//取出一个后,就发通知
					shareList.notify();
					
				}
				
			}
			
			
		}
	}
	
	public CustomerThread(List shareList){
		
		this.shareList = shareList;
	}
	
}

 

    通过构造函数把操作对象的List传进去,当List里面没有对象时,消费线程也就没什么可以消费的了,就要进入wait状态,当List里面有对象时,消费线程就消费一个,并发出notify的通知。

 

 4.Main:

package 生产_消费模型;

import java.util.LinkedList;
import java.util.List;

/**
 * 主函数
 * @author Administrator
 *
 */
public class Cb123456 {

	public static void main(String[] args) {
		//生产,消费线程交换的队列
		List shareList = new LinkedList();
		
		//启动生产线程
		new ProduceThread(shareList).start();
		
		//启动消费线程
		new CustomerThread(shareList).start();
	}
	
}

 

 

三、运行结果:

 

 

四、结果分析:

 1.Main里面,通过new关键字给LinkedList分配内存空间,同时实例化,但此时的LinkedList里面什么都没有,所以是生产线程先执行的

 2.在控制台可以看见在输出结果的时候,生产线程和消费线程总是同时显示结果的.

 

五、补充:

1.LinkedList:

 


 

2.null和" "

  其中null是表示没有地址.而" "表示是一个字符串,有地址的,但是字符串里面的内容却是空的,null就像没有锅,而" "表示有锅却没有米的

 

六、总结:

  生产消费模型:当集合中没有对象时,生产线程会产生一个,并发出通知,然后消费线程就把它给消费了。

队列生产消费模型是一种多线程编程模型,用于实现生产者-消费者模式。在该模型中,有两个线程:一个线程是生产者,另一个线程是消费者。生产者向队列中添加元素,而消费者从队列中移除元素。队列是一个共享资源,因此需要使用互斥锁条件变量来保证线程安全。 以下是使用C语言实现队列生产消费模型的示例代码: ```c #include <stdio.h> #include <stdlib.h> #include <pthread.h> #define MAX_QUEUE_SIZE 10 #define NUM_PRODUCERS 2 #define NUM_CONSUMERS 2 int queue[MAX_QUEUE_SIZE]; pthread_mutex_t mutex; pthread_cond_t cond_var; int queue_size = 0; int consumer_index = 0; int producer_index = 0; void *producer(void *arg) { int item; while (1) { item = rand() % 100; pthread_mutex_lock(&mutex); while (queue_size == MAX_QUEUE_SIZE) { pthread_cond_wait(&cond_var, &mutex); } queue[producer_index] = item; producer_index = (producer_index + 1) % MAX_QUEUE_SIZE; queue_size++; printf("Producer %d produced item %d\n", *((int *)arg), item); pthread_cond_broadcast(&cond_var); pthread_mutex_unlock(&mutex); } return NULL; } void *consumer(void *arg) { int item; while (1) { pthread_mutex_lock(&mutex); while (queue_size == 0) { pthread_cond_wait(&cond_var, &mutex); } item = queue[consumer_index]; consumer_index = (consumer_index + 1) % MAX_QUEUE_SIZE; queue_size--; printf("Consumer %d consumed item %d\n", *((int *)arg), item); pthread_cond_broadcast(&cond_var); pthread_mutex_unlock(&mutex); } return NULL; } int main() { pthread_t producers[NUM_PRODUCERS]; pthread_t consumers[NUM_CONSUMERS]; pthread_mutex_init(&mutex, NULL); pthread_cond_init(&cond_var, NULL); int i, producer_ids[NUM_PRODUCERS], consumer_ids[NUM_CONSUMERS]; for (i = 0; i < NUM_PRODUCERS; i++) { producer_ids[i] = i; pthread_create(&producers[i], NULL, producer, (void *)&producer_ids[i]); } for (i = 0; i < NUM_CONSUMERS; i++) { consumer_ids[i] = i; pthread_create(&consumers[i], NULL, consumer, (void *)&consumer_ids[i]); } for (i = 0; i < NUM_PRODUCERS; i++) { pthread_join(producers[i], NULL); } for (i = 0; i < NUM_CONSUMERS; i++) { pthread_join(consumers[i], NULL); } pthread_mutex_destroy(&mutex); pthread_cond_destroy(&cond_var); return 0; } ``` 在上面的代码中,生产者线程调用`producer()`函数,消费者线程调用`consumer()`函数。`producer()`函数随机生成一个整数,并将其添加到队列中。如果队列已满,则等待条件变量`cond_var`。`consumer()`函数从队列中移除一个元素。如果队列为空,则等待条件变量`cond_var`。 在`main()`函数中,创建多个生产消费者线程,然后等待它们完成。在生产消费者线程之间共享的队列上使用互斥锁条件变量来保证线程安全。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值