以下是使用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();
}
}