用java代码实现生产者和消费者的问题

public class ThreadDemo12 {
	public static void main(String[] args) {
		goods g=new goods();
		Product pro=new Product(g);
		Thread th1=new Thread(pro);
		th1.start();
		Customer cus=new Customer(g);
		Thread th2=new Thread(cus);
		th2.start();
	}

}
/**
 * 商品类
 * @author Al菜菜
 *
 */
class goods {
	private String name;
	private int num;

	public void setName(String name) {
		this.name = name;
	}

	public String getName() {
		return name;
	}

	public void setNum(int num) {
		this.num = num;
	}

	public int getNum() {
		return num;
	}
	/**
	 * 消费后将商品设为空值
	 */
	public void setEmpty(){
		this.name=null;
		this.num=0;
	}
	/**
	 * 判断是否有商品可以消费
	 * @return
	 */
	public boolean isEmpty(){
		return this.name==null&&this.num==0;
	}
}

class Product implements Runnable {
	private boolean flag = false;//用于循环生产商品
	private goods g;

	public Product(goods g) {
		this.g = g;
	}

	@Override
	public void run() {
		for (int i = 0; i < 30; i++) {
			synchronized (Object.class) { //线程锁
				if(!g.isEmpty()){
					try {
						Object.class.wait();  //当有商品没有被消费是,进入等待状态
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
				if (flag) {
					System.out.print("生产了商品一");
					g.setName("商品一");
					try {
						Thread.sleep(100); //用于在不使用锁的情况下,触发现象
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					System.out.println("生产了20个");
					g.setNum(20);
					flag=false;
				} else {
					System.out.print("生产了商品二");
					g.setName("商品二");
					try {
						Thread.sleep(100);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					System.out.println("生产了40个");
					g.setNum(40);
					flag=true;
				}
				Object.class.notify();
			}
		}
	}
}

class Customer implements Runnable {
	private goods g;

	public Customer(goods g) {
		this.g = g;
	}

	@Override
	public void run() {
		for(int i=0;i<30;i++){
			synchronized (Object.class) {
				if(g.isEmpty()){
					try {
						Object.class.wait();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
				System.out.println("消费商品:"+g.getName()+"数量:"+g.getNum());
				g.setEmpty();
				Object.class.notify();
			}
		}
	}
}


生产了商品一生产了20个
消费商品:商品一数量:20
生产了商品二生产了40个
消费商品:商品二数量:40
生产了商品一生产了20个
消费商品:商品一数量:20
生产了商品二生产了40个
消费商品:商品二数量:40
生产了商品一生产了20个
消费商品:商品一数量:20
生产了商品二生产了40个
消费商品:商品二数量:40
生产了商品一生产了20个
消费商品:商品一数量:20
生产了商品二生产了40个
消费商品:商品二数量:40
生产了商品一生产了20个
消费商品:商品一数量:20
生产了商品二生产了40个
消费商品:商品二数量:40
生产了商品一生产了20个
消费商品:商品一数量:20

......

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值