博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Producer-Consumer
阅读量:7112 次
发布时间:2019-06-28

本文共 1738 字,大约阅读时间需要 5 分钟。

  hot3.png

                                                                    Producer-Consumer

    很多时候生产者消费者速度不一致且差距比较大的情况下:生产者和消费者多线程设计模式,就可以考虑一下了。最关键的就是中间有一个缓冲的桥梁。(桥梁有两个限制,一个是装不下的情况,一个是取不出的情况)

//生产者代码public class MakerThread extends Thread {	private final Table table;	private static int id = 0;	public MakerThread(String name, Table table) {		super(name);		this.table = table;	}	public void run() {		try {			while (true) {				Thread.sleep(500);				String cake = "no." + nextId();				table.put(cake);			}		} catch (InterruptedException e) {		}	}	public synchronized int nextId() {		return id++;	}}
//消费者代码public class EaterThread extends Thread {	private final Table table;	public EaterThread(String name, Table table) {		super(name);		this.table = table;	}	public void run() {		try {			while (true) {				String cake = table.take();				Thread.sleep(1000);			}		} catch (InterruptedException e) {		}	}}
//中间的桥梁public class Table {	private final String [] buffer;	private int tail;	private int head;	private int count;		public Table(int count) {		this.buffer=new String [count];		this.head=0;		this.tail=0;		this.count=0;	}	//放不进的考虑	public synchronized void put(String cake) throws InterruptedException{		System.out.println(Thread.currentThread().getName()+" puts "+cake+" "+count);		while(count>=buffer.length){			wait();		}		buffer[tail]=cake;		tail=(tail+1)%buffer.length;		count++;		notifyAll();	}	//取不出的情况要有考虑	public synchronized String take() throws InterruptedException{		while(count<=0){			wait();		}		String cake=buffer[head];		head=(head+1)%buffer.length;		count--;		notifyAll();		System.out.println(Thread.currentThread().getName()+"take"+cake);		return cake;	}	}

    最负责的部分就是对桥梁的封装设计,对与每一个线程的操作都要一致,如何保证的情况下,就是考虑两种情况的同时,保证只有一个线程修改临界区(感觉已经有read-write的一点共同点,但没有抓住关键点)。

转载于:https://my.oschina.net/QAAQ/blog/667235

你可能感兴趣的文章
2015.7个人反思小结以及兴许规划
查看>>
云端数据遭觊觎 安全问题不容忽视
查看>>
编译gaia
查看>>
如何识别真Microsoft服务与非Microsoft服务来定位病毒自己的服务
查看>>
大数据之路- Hadoop环境搭建(Linux)
查看>>
解决问题:保存图片到本地文件夹后,在图库里看不到保存的图片问题。
查看>>
Android 源码分析(八) Launcher 桌面启动App过程
查看>>
BFS--POJ 1979
查看>>
day 19
查看>>
HMMPfam的安装使用手记(转载)
查看>>
使用 innotop 监控
查看>>
Android一 流
查看>>
掌阅之语----》记录
查看>>
Linux下ld搜索问题:ld: cannot find -l"XX"
查看>>
C++ 常用的字符串处理函数实现
查看>>
e.key && e.which && e.keyCode
查看>>
.NET静态变量与静态方法并发的问题
查看>>
51nod 1073 约瑟夫环
查看>>
【C#公共帮助类】枚举独特类
查看>>
poj - 1469 COURSES
查看>>