生产者消费者实例!!!

本人是小白,只是想留给自己看的,勿喷。。。

生产者类。。。

package aaa;
public class Shengchan implements Runnable {
private Protuct pro=null;
public Protuct getPro() {
	return pro;
}
public void setPro(Protuct pro) {
	this.pro = pro;
}
public Shengchan(Protuct pro) {
	super();
	this.pro = pro;
}
public void run() {
	 for (int i = 0; i < 10; i++) {  
		  
         try {  
        	 pro.shangchan();
         } catch (Exception e) {  
             e.printStackTrace();  
         }  
 
    }  
}
} 

消费者类。。。

package aaa;
public class xiaofei implements Runnable {
private Protuct pro=null;
public Protuct getPro() {
	return pro;
}
public void setPro(Protuct pro) {
	this.pro = pro;
}
public xiaofei(Protuct pro) {
	super();
	this.pro = pro;
}
public void run() {
	 for (int i = 0; i < 10; i++) {  
		  
         try {  
        	 pro.xiaofei();
         } catch (Exception e) {  
             e.printStackTrace();  
         }  
 
     }  
}
}
工厂类

package aaa;

public class Protuct {
	private String name;
	private int count;
	private boolean flag;
	public synchronized void shangchan() throws InterruptedException{
		if(count==10){
			System.out.println("仓库已满");
			wait();
		}
		count++;
		Thread.sleep(3000);
		System.out.println("生产了一个产品");
		notify();
	}
	public synchronized void xiaofei() throws InterruptedException{
		if(count==0){
			System.out.println("没有产品,等待生产");
			wait();
		}
		count--;
		Thread.sleep(300);
		System.out.println("消费了一个产品");
		notify();
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getCount() {
		return count;
	}
	public void setCount(int count) {
		this.count = count;
	}
	public boolean isFlag() {
		return flag;
	}
	public void setFlag(boolean flag) {
		this.flag = flag;
	}
}

测试类

package aaa;

public class test {
	public static void main(String[] args) {
		Protuct pro=new Protuct();
		Shengchan sheng=new Shengchan(pro);
		xiaofei xiao=new xiaofei(pro);
		sheng.run();
		xiao.run();
	}
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值