首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

生产者消费者形式详解及代码实现

2013-10-01 
生产者消费者模式详解及代码实现生产者消费者模式说明:1.生产者只在仓库未满时进行生产,仓库满时生产者进

生产者消费者模式详解及代码实现

生产者消费者模式说明:

1.生产者只在仓库未满时进行生产,仓库满时生产者进程被阻塞;

2.消费者只在仓库非空时进行消费,仓库为空时消费者进程被阻塞;

3.当消费者发现仓库为空时会通知生产者生产;

4.当生产者发现仓库满时会通知消费者消费;

实现的关键:

共享内存中的两个同步方法,及同步方法中wait()方法的调用,同步保证了对象只能被一个线程占用,wait保证了当线程在等待过程中释放锁,使得其他对象有机会获得锁。

在一个对象中,用synchonized声明的方法为同步方法。Java中有一个同步模型-监视器,负责管理线程对对象中的同步方法的访问,它的原理是:赋予该对象唯一一把'钥匙',当多个线程进入对象,只有取得该对象钥匙的线程才可以访问同步方法,其它线程在该对象中等待,直到该线程用wait()方法放弃这把钥匙,其它等待的线程抢占该钥匙,抢占到钥匙的线程后才可得以执行,而没有取得钥匙的线程仍被阻塞在该对象中等待。 总而言之,synchonized使得只有一个线程能进入临界代码区。

代码实现:

array empty.produce: 86consume: 86array empty.produce: 232consume: 232array empty.produce: 438consume: 438produce: 272consume: 272array empty.produce: 495consume: 495produce: 354produce: 533consume: 354produce: 92consume: 533produce: 374consume: 92produce: 441produce: 141consume: 374consume: 441consume: 141array empty.produce: 68consume: 68produce: 978consume: 978array empty.produce: 737consume: 737array empty.produce: 904consume: 904array empty.produce: 613consume: 613array empty.produce: 812consume: 812produce: 726produce: 326consume: 726produce: 305consume: 326consume: 305

待续:BlockingQueue实现生产者消费者模式

参考资料:

http://programming.iteye.com/blog/158568http://www.cnblogs.com/mengyan/archive/2012/08/30/2664352.htmlhttp://developer.51cto.com/art/201202/317209.htmhttp://canofy.iteye.com/blog/411408http://www.blogjava.net/xylz/archive/2010/07/09/325612.html

热点排行