导航

多线程-生产者消费者模式

Posted on 2017-09-06 15:07  HerlerTn  阅读(172)  评论(0)    收藏  举报

生产者-消费者模式,是学习多线程中很多人都会遇到经典模式。

场景:当生产者生产出产品,消费者负责销售。这时要用到多线程,将生产者看成一个线程,消费者看成一个线程,产品看成一个类(这里的产品类用到了面向对象的思想)。

代码:生产者

class Maker extends Thread{
private Product product;

public Product getProduct() {
return product;
}

public void setProduct(Product product) {
this.product = product;
}

@Override
public void run() {
while (true){
product.Make();
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
消费者
//消费者
class Saler extends Thread{
private Product product;

public Product getProduct() {
return product;
}

public void setProduct(Product product) {
this.product = product;
}

@Override
public void run() {
while (true){
product.Sale();
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

产品类
//产品类
class Product {
private int num=0;
Random r=new Random();
//生产产品方法
public synchronized void Make(){
if (this.num==0){
this.num=r.nextInt(10)+1;
System.out.println("生产产品"+num+"个");
}
this.notify();
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//销售产品方法
public synchronized void Sale(){
if (this.num>0){
int i=r.nextInt(num)+1;
System.out.println("出售产品"+i+"个");
num -=i;
}
if (this.num==0){
this.notify();
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}



测试
public class SandX {
public static void main(String[] args) {
Product product=new Product();
Maker maker=new Maker();
Saler saler=new Saler();
maker.setProduct(product);
saler.setProduct(product);
maker.start();
saler.start();
}
}

结果: