java 生产者消费者模型(多对多)

package com.sunle.thread;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
 * 生产者,消费者模式,多对多。
 *
 * @author 孙乐
 *
 */
public class ProducerAndConsumer {
 public static void main(String[] args){
  
 SuperMarket sm=new SuperMarket();
 Producer p1=new Producer(sm);
 
 Producer p2=new Producer(sm);
 Consumer c1=new Consumer(sm);
 Consumer c2=new Consumer(sm);
 Consumer c3=new Consumer(sm);

 Thread th1=new Thread(p1);
 Thread th2=new Thread(p2);

 
 Thread th3=new Thread(c1);
 Thread th4=new Thread(c2);
 Thread th5=new Thread(c3);

  //多个生产者
  th2.start();
  th1.start();
  //多个消费者
  th3.start();
  th4.start();
  th5.start();
 }
}
//超级市场类
class SuperMarket{
 List list=new ArrayList<>(); //商品
  int i=0;    //生产次数统计
  
  int j=0;    //消费次数统计
  
 boolean flag=true;
 public synchronized void Add(){
  while(list.size()>3){   //当产品比较多时就暂停生产
   try {
    this.wait();
   } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
  }
  i++;
  list.add("aaaaaaa"+i);

  System.out.println("添加--"+i);
  this.notifyAll(); 


 }

//消费者类
 public synchronized void del(){
  

  System.out.println("删除标记方法");

  while (list.isEmpty()) {
   
   if (j==10) { 
    flag = false;//若消费完了,告诉外面的线程可以退出了

    return;  //因为是while()方法,防止死循环,退出方法。
   }

   try {
    System.out.println("删除方法wait()执行标记");
    this.wait();
   } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();

   }

  }
  for(int i=list.size();i>0;i--){

  System.out.println(list.get(i-1)+"删除");
   list.remove(i-1);
   j++;     //统计消费次数
  }
  
  this.notifyAll();
  

 }
 
}
//生产者类
class Producer implements Runnable {
 
 SuperMarket sm;
 
 public Producer(SuperMarket sm) {
  this.sm=sm;
 }
   //生产者
 public void run(){
   for(int i=0;i<5;i++){
    sm.Add();
    
   }


 }
}

//消费者类
class Consumer implements Runnable{
 
 SuperMarket sm;
 
 public Consumer(SuperMarket sm) {
  this.sm=sm;
 }
 //消费者
 public void run(){
  
  while (sm.list!=null) {
   //没有产品了就可以退出了
   if(!sm.flag){
    System.out.println("退出线程!!!!!!!");
    
    return;
    
   }
   System.out.println(sm.j);
   sm.del();
    
   }

  }

}

 

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值