java再复习——线程的经典问题-生产者消费者

为什么多线程总是离不开这个问题呢?

因为这种场景是多线程在生成环境中最重要,最主要的应用,基于这种场景提炼出的问题就是生产者消费者问题。

实例代码:

/**
 * 资源
 * @author PC
 *
 */
class Resource {
	int count = 0;
	boolean isHas = false;
	
	public synchronized void product() throws InterruptedException{
		while(isHas){
				wait(); //为了方便阅读 ,异常直接抛出了。
		}
		System.out.println(Thread.currentThread().getName() + "..生成了商品【"+(++count)+"】----");
		isHas = true;
		notifyAll();
	}
	
	public synchronized void consume() throws InterruptedException{
		while(!isHas){
			wait();
		}
		System.out.println(Thread.currentThread().getName() + "..消费了商品【"+count+"】");
		isHas = false;
		notifyAll();
	}
}

/**
 * 生产者
 * @author PC
 *
 */
class Producer implements Runnable{
	
	Resource resource;
	
	public Producer(Resource resource){
		this.resource = resource;
	}

	public void run() {
		while (true) {
			try {
				resource.product();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
	
}

/**
 * 消费者
 * @author PC
 *
 */
class Consumer implements Runnable{
	
	Resource resource;
	
	public Consumer(Resource resource){
		this.resource = resource;
	}

	public void run() {
		while (true) {
			try {
				resource.consume();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
	
}


测试代码:

public class ProducerConsumerDemo {

	public static void main(String[] args) {
		Resource resource = new Resource();
		new Thread(new Producer(resource)).start();
		new Thread(new Producer(resource)).start();
		new Thread(new Consumer(resource)).start();
		new Thread(new Consumer(resource)).start();
	}
	
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值