生产者——消费者问题

线程间的通讯问题及Object类的支持
在这里插入图片描述
在这里插入图片描述

范例:初步实现生产者与消费者问题

class Info {
	private String title;
	private String content;
	public String getTitle() {
		return title;
	}
	public void setTitle(String title) {
		this.title = title;
	}
	public String getContent() {
		return content;
	}
	public void setContent(String content) {
		this.content = content;
	}
}
class Productor implements Runnable{
	private Info info = null;
	public Productor(Info info){
		this.info=info;
	}
	public void run(){
		for(int x=0;x<50;x++){
			if(x%2==0){
				this.info.setTitle("陶帅帅");
				try {
					Thread.sleep(100);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				this.info.setContent("一个小帅哥");
				
			}else{
				this.info.setTitle("可爱的小动物");
				try {
					Thread.sleep(100);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				this.info.setContent("草泥马");
			}
		}
	}
}
class Consumer implements Runnable{
	private Info info;
	public Consumer (Info info){
		this.info=info;
	}
	public void run(){
		for(int x=0;x<50;x++){
			try {
				Thread.sleep(100);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			System.out.println(this.info.getTitle()+"-->"+this.info.getContent());
		}
	}
}
public class Hello{
	public static void main(String args[]) {
		Info info = new Info();
		Productor p = new Productor(info);
		Consumer c = new Consumer(info);
		new Thread(p).start();
		new Thread(c).start();
	}
}

在这里插入图片描述

解决数据不同步问题

要想解决同步问题一定使用同步代码块或者是同步方法,既然要同步,那么肯定将设置属性和取得属性的内容都统一交给Info类完成。

class Info {
	private String title;
	private String content;
	public synchronized void set(String title,String content){
		this.title=title;
		try {
			Thread.sleep(100);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		this.content=content;
	}
	public synchronized void get(){	
		System.out.println(this.title+"-->"+this.content);
	}
}
class Productor implements Runnable{
	private Info info = null;
	public Productor(Info info){
		this.info=info;
	}
	public void run(){
		for(int x=0;x<50;x++){
			if(x%2==0){
				this.info.set("陶帅帅", "一个小帅哥");
			}else{
				this.info.set("草泥马", "可爱的小动物");
			}
		}
	}
}
class Consumer implements Runnable{
	private Info info;
	public Consumer (Info info){
		this.info=info;
	}
	public void run(){
		for(int x=0;x<50;x++){
			this.info.get();	
		}
	}
}
public class Hello{
	public static void main(String args[]) {
		Info info = new Info();
		Productor p = new Productor(info);
		Consumer c = new Consumer(info);
		new Thread(p).start();
		new Thread(c).start();
	}
}

所有的设置和取得数据的操作都交给了同步的方法完成。
现在同步的问题解决了,但是重复的操作更严重了。

解决重复问题

在这里插入图片描述
在这里插入图片描述
![在这里插入图片描述](https://img-blog.csdnimg.cn/20190609182101927.png
范例:修改Info类

class Info {
	private String title;
	private String content;
	private boolean flag = true;
	//flag=true,表示可以生产不可以取
	//flag=false,表示可以取走不允许生产
	public synchronized void set(String title,String content){
		if (this.flag==false){//表示已经生产未取走
			try {
				super.wait();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}//没有生产过,可以生产
		this.title=title;
		try {
			Thread.sleep(100);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		this.content=content;
		this.flag=false;//表示生产过了
		super.notify();
	}
	public synchronized void get(){	
		if(this.flag==true){
			try {
				super.wait();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		try {
			Thread.sleep(100);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println(this.title+"-->"+this.content);
		this.flag=true;//表示取过了
		super.notify();
	}
}

面试题:请解释sleep()与wait()的区别?
在这里插入图片描述
方法来唤醒

总结

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
生产者-消费者问题是一个经典的同步问题,描述了多个线程之间共享固定大小缓冲区的情境。生产者将数据放入缓冲区,而消费者则从缓冲区中取出数据。下面是一个简单的算法实现: ```python import threading import time # 缓冲区大小 BUFFER_SIZE = 10 # 缓冲区 buffer = [] # 生产者线程 class ProducerThread(threading.Thread): def run(self): global buffer while True: # 等待一段时间 time.sleep(1) # 生产一个数据 data = time.time() # 获取锁 lock.acquire() # 判断缓冲区是否已满 if len(buffer) < BUFFER_SIZE: # 将数据放入缓冲区 buffer.append(data) print("Produced", data) else: print("Buffer is full") # 释放锁 lock.release() # 消费者线程 class ConsumerThread(threading.Thread): def run(self): global buffer while True: # 等待一段时间 time.sleep(2) # 获取锁 lock.acquire() # 判断缓冲区是否为空 if len(buffer) > 0: # 从缓冲区中取出数据 data = buffer.pop(0) print("Consumed", data) else: print("Buffer is empty") # 释放锁 lock.release() # 创建锁 lock = threading.Lock() # 创建生产者线程和消费者线程 producer_thread = ProducerThread() consumer_thread = ConsumerThread() # 启动线程 producer_thread.start() consumer_thread.start() ``` 上面的代码中,我们使用了 Python 的 threading 模块来创建线程。ProducerThread 类表示生产者线程,ConsumerThread 类表示消费者线程。在 run() 方法中,生产者线程等待一段时间后生成一个数据,如果缓冲区未满,则将数据放入缓冲区中;消费者线程等待一段时间后从缓冲区中取出一个数据,如果缓冲区非空,则将数据取出并打印。 在生产者消费者线程访问缓冲区时,我们使用了一个 Lock 对象来进行同步。Lock 对象可以确保在同一时间只有一个线程能够访问共享资源。在获取锁之前,线程会一直等待,直到锁被释放。在释放锁之后,其他线程才能获取锁并访问共享资源。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值