多线程生产者与消费者问题代码模型

package li.com.thread02;

//生产者与消费者 问题的引出
class Info{
	     private String title;
	     private String content;
	     private boolean flag=true;  //flag =true表示可以生产 不允许消费取出   flag=false表示可以取出 不可以生产
		
	     //设置数据 (生产者)
		public synchronized void set(String title,String content) {  //synchronized 解决数据错位问题  保证title 和content同事完成
             if(this.flag==false){  //如果重复进入到set()方法 发现不能生产所以到等待。
            	  try {
					super.wait();
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
             }
             
			this.title = title;
			 try {
					Thread.sleep(100);   //休眠
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			this.content=content;
			
			//生产完毕修改生产标记
			this.flag=false;
			//换新等待线程、
			super.notify();
			
		}
		public synchronized void get() {  //保证数据同步取出
			
			if(this.flag){  //表示还没有生产  无法取出  所以要等待
				try {
					super.wait();
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			 try {
				Thread.sleep(300);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		    System.out.println(this.title+"---------"+this.content);
		    
		    //修改生产标记
		    this.flag=true;
		    //换醒等待线程
		    super.notify();
		}
		
	     
	     
}

class Producer implements Runnable{
	
	 private Info info;
	 
	 public Producer(Info info){
		 this.info=info;
	 }

	@Override
	public void run() {
		
		 for (int i = 0; i <200; i++) {
			
			 if(i%2==0){
				 
				 this.info.set("李成双","是个好学生");

			 }else{
				 this.info.set("王大崔","好农民");
			 }
			
			 System.out.println("生产。。。。。。"+i);
		 
		}
		
	}
	
	
}


//消费
class Consumption implements Runnable{
    private Info info;
    
    public Consumption(Info info){
    	this.info=info;
    }
    
	@Override
	public void run() {
	   
	
		 for(int i=0;i<200;i++){
			
			this.info.get();
		 }
		
	}
	
	
}

public class ProCon {

	public static void main(String[] args) {
	     
		 Info info=new Info();
		 new Thread(new Producer(info)).start();
		 new Thread(new Consumption(info)).start();
		 

	}

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值