生产者--消费者模式

news/2024/7/3 10:19:53 标签: java

生产者--消费者模式

1、示例:

java">class Resource{
	private String name;
	private int count = 1;
	private Boolean flag = false;
	
	public synchronized void set(String name){
		if(flag)
			try {
				this.wait();//this代表调用函数线程
			} catch (InterruptedException e) {}
		
		this.name = name+"__ " + count++;
		System.out.println(Thread.currentThread().getName()+ "......生产者" + this.name);
		flag = true;
		this.notifyAll();
	}
	
	public synchronized void show(){
		if(!flag)
			try {
				this.wait();
			} catch (InterruptedException e) {
			}
		
		System.out.println(Thread.currentThread().getName()+"消费者"+ this.name);
		flag = false;
		this.notifyAll();
	}
}

//定义生产类Producter,生产商品

class Producter implements Runnable{
	private Resource r;
	Producter(Resource r){
		this.r = r;
	}
	public void run(){
		while(true){
			r.set("商品");
		}
	}
}

//定义消费者类Customer,消费商品
class Customer implements Runnable{
	private Resource r;
	Customer(Resource r){
		this.r = r;
	}
	public void run(){
		while(true){
			r.show();
		}
	}
}

分析: 

  • 多个生产者、消费者定义使用while判断标记

    原因:让被唤醒的线程再次判断标记

  • 定义中使用notifyAll

    原因: 因为需要唤醒对方线程,如果使用notify容易出现值唤醒本方线程的情况,导致线程中所有线程都处于等待状态

 

2.JDK5中提供多线程解决方案

  • 将同步synchronized替换成lock操作
  • 将object中的wait/notify/notifyALl替换成condtion对象
  • 该对象可以通过lock锁进行获取

 

示例:

 

 

java">package unit18;

import java.util.concurrent.locks.*;

class Resources{
	private String name;
	private int count = 1;
	private Boolean flag = false;
	
	private Lock lock = new ReentrantLock();//定义Lock类
	
	private Condition condition_pro = lock.newCondition();
	private Condition condition_con = lock.newCondition();
	
	public  void set(String name)throws InterruptedException{
		lock.lock();//添加锁
		try{
		while(flag){
			condition_pro.wait();//生产者调用线程等待
		  }
		this.name = name+"__ " + count++;
		System.out.println(Thread.currentThread().getName()+ "......生产者" + this.name);
		flag = true;
		condition_pro.signal();	//唤醒消费者线程
		}catch(Exception e){}
		finally{
			lock.unlock();//解锁
		}
	}
	
	public synchronized void show()throws InterruptedException{
		lock.lock();
		try{
		while(!flag){
			condition_con.wait();
		}
		
		System.out.println(Thread.currentThread().getName()+"消费者"+ this.name);
		flag = false;
		condition_con.signal();//唤醒生产者线程
		}catch(Exception e){}
		finally{
			lock.unlock();
		}
	}
}


class Producters implements Runnable{
	private Resources r;
	Producters(Resources r){
		this.r = r;
	}
	public void run(){
		while(true){
			try {
				r.set("商品");
			} catch (InterruptedException e) {
			
			}
		}
	}
}

class Customers implements Runnable{
	private Resources r;
	Customers(Resources r){
		this.r = r;
	}
	public void run(){
		while(true){
			try {
				r.show();
			} catch (InterruptedException e) {
			
			}
		}
	}
}




public class ProducterCustomerTest2 {

	public static void main(String[] args) {
		Resources r = new Resources();
		Producters pro = new Producters(r);
		Customers cus = new Customers(r);
		Thread t1 = new Thread(pro);
//		Thread t2 = new Thread(pro);
//		Thread t3 = new Thread(cus);
		Thread t2 = new Thread(cus);
		t1.start();
//		t2.start();
//		t3.start();
		t2.start();
	}


}

  

 

转载于:https://www.cnblogs.com/chizhongyue/p/4606074.html


http://www.niftyadmin.cn/n/1153072.html

相关文章

C++中的预定义宏

C/C++宏大全(转载,原贴地址http://www.cnblogs.com/sevencat/archive/2004/06/10/14872.html)一、标准预定义宏The standard predefined macros are specified by the relevant language standards, so they are available with all compilers that impl…

PHP 7.0 中各种 Hash 速度比较

概述 最近需要对一些很长的 msyql 字段做索引优化。讨论下来有几种解决方案带确定,其中一个就是对现有字符做 hash,然后对此hash和原始字符做联合索引。就此有了 hash 效率比较的需求,文中使用 php 对一段字符做 200 万次 hash,并…

NPOI兼容 excel2003,2007版本

根据项目需要&#xff0c;需要对excel进行导入导出&#xff0c;所以选择NPOI&#xff0c;优点在这里就不详细介绍了&#xff0c;下面进入正题。 1 public int Import(string path)2 {3 IList<Student> list new List<Student>();4 5 …

解决 Zend Studio For Linux 乱码和UBUNTU下不显示(白屏)问题

不显示界面问题&#xff1a;打开后不能正常显示&#xff0c;只有标题栏正常解决&#xff1a;用vi打开Zend_Development_Environment&#xff08;和你选择安装的路径有关&#xff0c;找下&#xff09;&#xff0c;打开后输入/set nu在输入1693在其附近会有类似下面的代码&#x…

CCRD_TOC_2008年第3期

中信国健临床通讯 2008年第3期 目 录 银屑病和银屑病关节炎 1. 国际皮肤病专家呼吁重视生物制剂治疗银屑病 原文: http://pharmatimes.com/forums/forums/t/855.aspx 2. 案例报道&#xff1a;依那西普有效治疗泛发性脓疱型银屑病 Esposito M, et al. Dermato…

Ubuntu无线上网

sudo apt-get install bcm43xx-fwcutter&#xff0c;不但自动安装了fwcutter工具&#xff08;这个工具本来是从windows driver .sys文件中分离出firmware的&#xff09;&#xff0c;而且还主动提示我要不要直接从网上下载firmware本身。回答yes就一切完成&#xff08;自动下载了…

Linux 之secureCRT连接SSH

1.登陆linux系统&#xff0c;打开终端命令。输入 rpm -qa |grep ssh 查找当前系统是否已经安装。 2.如果没有安装SSH软件包&#xff0c;可以通过yum 或rpm安装包进行安装。 .3.安装好了之后&#xff0c;就开启ssh服务。Ssh服务一般叫做 sshd&#xff0c;命令行输入 service s…

手机触屏的js事件

处理Touch事件能让你跟踪用户的每一根手指的位置。你可以绑定以下四种Touch事件&#xff1a;1.touchstart: // 手指放到屏幕上的时候触发 2.touchmove: // 手指在屏幕上移动的时候触发 3.touchend: // 手指从屏幕上拿起的时候触发 4touchcancel: // 系统取消touch事件的时候…