首页 > 编程语言 > 详细

多线程的生产者和消费者

时间:2020-04-06 20:09:58      阅读:68      评论:0      收藏:0      [点我收藏+]

以下是使用JUC的BlockingQueue,生产者生产娃哈哈矿泉水和旺仔小馒头:

import java.util.concurrent.BlockingQueue;
public class ProducerQueue implements Runnable {

public int number = 10;

private BlockingQueue<Goods> blockingQueue;

public ProducerQueue(BlockingQueue blockingQueue){
    this.blockingQueue = blockingQueue;
}

@Override
public void run(){
    for (int i=0;i<number;i++){
        Goods goods = null;
        if(i%2==0){
            goods = new Goods("娃哈哈", "矿泉水");
        }else {
            goods = new Goods("旺仔", "小馒头");
        }
        System.out.println("生产者开始生产商品:"+goods.getBrand()+"--"+goods.getName());
        try{
            blockingQueue.put(goods);
        }catch (InterruptedException e){
            e.printStackTrace();
        }
    }
}

}

生产者所生产的商品
public class Goods {

private String name;
private String brand;

public Goods(String name, String brand) {

    this.name = name;
    this.brand = brand;
}

public String getBrand() {
    return brand;
}

public void setBrand(String brand) {
    this.brand = brand;
}

public String getName() {
    return name;
}

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

}

以下是两个消费者开始消费商品:
import java.util.concurrent.*;

public class TestProducerConsumer {

public static void main(String[] args){

    // 使用可缓存线程池
    ExecutorService executorService = Executors.newCachedThreadPool();
    BlockingQueue<Goods> queue = new ArrayBlockingQueue<>(5);
    ProducerQueue producerQueue = new ProducerQueue(queue);
    ConsumerQueue consumerQueue = new ConsumerQueue(queue);
    executorService.execute(producerQueue);
    executorService.execute(consumerQueue);
    executorService.shutdown();
}

}

多线程的生产者和消费者

原文:https://www.cnblogs.com/yyml181231/p/12643569.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!