java 多个消费者_java线程之多个生产者消费者2.0

/*ProducterConsumerDemo解决了只有两个线程共享资源的生产消费问题,主要利用标志位的互斥解决

本程序致力于解决多出现多个生产者,多个消费者的时候,依然能够达到生产一次,消费一次的功能

解决的方法就是:1)在被唤醒之后仍然进行条件判断,去检查要改的数字是否满足条件,如果不满足条件就继续睡眠。把两个方法中的if改为while即可。

当然,此时仍会出现问题,就是所以线程都等待,失去资格

2)需要将notify()改成notifyAll()*/

classProducterConsumerDemo2

{public static voidmain(String[] args)

{

Resources r=newResources();

Productor pro=newProductor(r);

Consumer con= newConsumer(r);

Thread t1=newThread(pro);

Thread t2=new Thread(pro);//多个生产者

Thread t3 =newThread(con);

Thread t4=new Thread(con);//多个消费者

t1.start();

t2.start();

t3.start();

t4.start();

System.out.println("Hello World!");

}

}classResources

{privateString name;private int count =1;private boolean flag =false;public synchronized voidset(String name)

{//1)循环判断

while(flag)try{this.wait();}catch(Exception e){}this.name = name+"--"+count++;

System.out.println(Thread.currentThread().getName()+"生产者"+this.name);

flag=true;//2)唤醒所有进程

this.notifyAll();

}public synchronized voidout()

{//1)循环判断

while(!flag)try{this.wait();}catch(Exception e){}

System.out.println(Thread.currentThread().getName()+" ....消费者...."+this.name);

flag=false;//2)唤醒所有进程

this.notifyAll();

}

}class Productor implementsRunnable

{privateResources res;

Productor(Resources res){this.res =res;

}public voidrun(){while(true){

res.set("++商品++");

}

}

}class Consumer implementsRunnable

{privateResources res;

Consumer(Resources res){this.res =res;

}public voidrun(){while(true){

res.out();

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值