多线程,生产者和消费者

黑马程序员---------多线程间数据传输编程

------Java培训、Android培训、iOS培训、.Net培训、期待与您交流! -------



题目:编写一个多线程程序,模拟2个生产者生产产品,3个消费者消费产品。2个生产者不停的生产商品3个消费者不停的消费产品。
分析:
 *两个生产者,3个消费者,同样的操作一种数据,而且必须是产品大于0才可以
 *可以生产一个出来消费一个。
 *这个是多线程,并且进行多线程之间的数据共享
 */
public class Test31 {


public static void main(String[] args) {

Product p=new Product();//
Producer pro =new Producer(p);//生产者
Consumer con=new Consumer(p);//消费者
Thread t1=new Thread(pro);
Thread t2=new Thread(pro);
Thread t3=new Thread(con);
Thread t4=new Thread(con);
Thread t5=new Thread(con);
t1.start();
t2.start();
t3.start();
t4.start();
t5.start();
}


}
class Product
{
private int product=0;//产品数量
boolean flag =false;//标志位
public synchronized void set()
{
while(flag)
try{this.wait();}catch(Exception e){}
product ++;
System.out.println("生产者:"+Thread.currentThread().getName()+"生产产品数量:1,剩余产品数量---"+product);
flag=true;
this.notifyAll();

}
public synchronized void out()//同步方法
{
 while(!flag)
try{this.wait();}catch(Exception e){}//线程等待
     if(product>0)
     {
    System.out.println("消费者:"+Thread.currentThread().getName()+"消费产品数量1,剩余产品数量"+--product);
    flag =false;
      this.notifyAll();//线程唤醒
     }
     else
     {
        System.out.println("消费者:"+Thread.currentThread().getName()+"没有产品");
    flag =false;
    this.notifyAll();
     }
}
}


class Producer implements Runnable
{
//
private Product p;
Producer(Product p){
this.p=p;  
}
public void run() {

while(true){
p.set();
}
}
}
class Consumer implements Runnable
{
private Product p;
Consumer(Product p){
this.p=p;
}


public void run() {
// TODO Auto-generated method stub
while(true){
p.out();
}
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值