您的位置:首页 > 编程语言 > Java开发

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

2017-03-08 10:13 453 查看
为什么多线程总是离不开这个问题呢?

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

实例代码:

/**
* 资源
* @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();
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: