黑马程序员技术交流社区
标题:
多生产者 消费者 同步代码
[打印本页]
作者:
vermouth
时间:
2015-1-16 16:33
标题:
多生产者 消费者 同步代码
多消费者 多生产者
同时生产和消费,最大库存量20.
将生产和消费放到两个实现了Runnable类中,使多个他们能够同时运行
在Resource类中,单例模式创建仓库资源实例,
实现了生产和消费两个方法,使用synchronized同步方法
full和empty控制库存量决定是否能够生产和消费,使用while循环wait判断条件,notify通知所有等待线程能够使用共享数据。
没有用到1.5封装的同步对象,只为了熟悉生产者消费者的经典模型,多多指教
public class PCRDemo{
public static void main(String [] args){
Producer p = new Producer();
Customer c = new Customer();
Thread t1 = new Thread(p);
Thread t2 = new Thread(p);
Thread t3 = new Thread(p);
Thread t4 = new Thread(c);
Thread t5 = new Thread(c);
Thread t6 = new Thread(c);
t1.start();
t2.start();
t3.start();
t4.start();
t5.start();
t6.start();
}
}
class Resource{
private static Resource resource = null;
public boolean empty = true ;
public boolean full = false ;
private String resName = "res";
public int count = 0;
private Resource(){}
public static Resource getInstance(){
if(resource == null){
synchronized(Resource.class){
if(resource == null)
resource = new Resource();
}
}
return resource;
}
public synchronized void produce(){
while (full){
try{
this.wait();
}
catch(Exception e){
throw new RuntimeException("It is full!");
}
}
count ++;
String name = resName+"-"+ count;
System.out.println(Thread.currentThread().getName()+": Produce "+name+" It has "+count+"Resources ");
empty = false;
if(count>=20){
full = true;
}
notifyAll();
try{
Thread.sleep(60);
}
catch(Exception e){
}
}
public synchronized void consume(){
while (empty){
try{
this.wait();
}
catch(Exception e){
}
}
String name = resName+"-"+ count;
count --;
System.out.println(Thread.currentThread().getName()+": Consume "+name+" It has "+count+"Resources ");
full = false;
if(count <= 0){
empty=true;
}
notifyAll();
try{
Thread.sleep(10);
}
catch(Exception e){
}
}
}
class Producer implements Runnable{
private Resource resource = Resource.getInstance();
public void run(){
while (true)
resource.produce();
}
}
class Customer implements Runnable{
private Resource resource = Resource.getInstance();
public void run(){
while (true)
resource.consume();
}
}
复制代码
作者:
兮兮之c
时间:
2015-1-24 23:46
哇,你写的真好,不过还是有几点感觉有点问题,(1)单例模式的话,你应该私有化Resource类的构造方法,但是你没有。(2)感觉你那个empty和full没什么用,完全可以使用count进行判断。其他觉得写得都非常好,例如单例模式的双if,而且使用了类级别的锁,还有生产和消费方法中用while进行循环判断,很不错。
作者:
vermouth
时间:
2015-1-25 12:11
兮兮之c 发表于 2015-1-24 23:46
哇,你写的真好,不过还是有几点感觉有点问题,(1)单例模式的话,你应该私有化Resource类的构造方法,但 ...
29 行 是单例的构造方法私有化
使用empty和full是自己在写代码时候,下意识使用锁的思想,大概用count会没那种感觉
谢谢指导~
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2