java_多线程_解决生产者消费者问题_用最简单的代码

/**
 * java_解决生产者消费者问题_用最简单的代码
 * 库存最大是10,每生产10个开始消费,消费完再生产
 * 
 */
package 重要练习0922;

public class 生产者消费者问题 {
	public static void main(String[] args) {
		product p = new product();
		new Thread(new Produce(p)).start();
		new Thread(new Customer(p)).start();
	}
}

class product {
	public static int KU_CUN_LIANG_MAX = 10;
	public static int xianYouLiang = 0;

	public void producer() {
		synchronized (this) {
			if (this.xianYouLiang >= this.KU_CUN_LIANG_MAX) {
				try {
					this.wait();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			this.xianYouLiang++;
			// 让他生产的快一点
			// try {
			// Thread.sleep(1000);
			// } catch (InterruptedException e) {
			// e.printStackTrace();
			// }
			System.out.println("生产了第:" + this.xianYouLiang + "件");

			if (this.xianYouLiang == this.KU_CUN_LIANG_MAX) {
				this.notify();
			}
		}
	}

	public void customer() {
		synchronized (this) {
			if (product.xianYouLiang <= 0) {
				try {
					this.wait();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			System.out.println("消费了第:" + this.xianYouLiang + "件");
			this.xianYouLiang--;
			if (this.xianYouLiang == 0) {
				this.notify();
			}
		}
	}

}

class Produce implements Runnable {
	product p;

	public Produce(product p) {
		this.p = p;
	}

	@Override
	public void run() {
		while (true) {
			p.producer();
		}

	}

}

class Customer implements Runnable {
	product p;

	public Customer(product p) {
		this.p = p;
	}

	@Override
	public void run() {
		while (true) {
			p.customer();
		}
	}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值