java多线程笔记–生产者消费者模型
文章目录
参考:
https://www.cnblogs.com/jiangyang/p/6007030.html
http://www.importnew.com/27063.html
https://juejin.im/entry/596343686fb9a06bbd6f888c
1.利用BlockingQueue实现
/**
* @Description: 1)使用阻塞队列BlockingQueue实现生产者消费者模型
* 2)由于操作“出队/入队+日志输出”不是原子的,所以上述日志的绝对顺序与实际的出队/入队顺序有出入
* 3)同一产品的消费一定发生在生产之后
* @Author:
* @Date: 2019/5/27 0:43
*/
public class PCByBlockingQueue {
public static void main(String[] args) {
Factory factory = new Factory(10);
new Thread(factory.NewProducer()).start();
new Thread(factory.NewProducer()).start();
new Thread(factory.NewConsuner()).start();
new Thread(factory.NewConsuner()).start();
}
public static class Factory {
private final AtomicInteger increNo = new AtomicInteger(0);
private BlockingQueue<Product> resourceQueue;
public Factory(int capacity) {
this.resourceQueue = new LinkedBlockingQueue<>(capacity);
}
public Producer NewProducer() {
return new Producer();
}
public Consuner NewConsuner() {
return new Consuner();
}
private class Product {
public int id;
public Product(int id) {
this.id = id;
}
}
private class Producer implements Runnable {
@Override
public void run() {
while (true) {
try {
// 随机延时模拟生产端逻辑耗时(long) (Math.random() * 1000)
Thread.sleep((long) (Math.random() * 1000));
Product product = new Product(increNo.getAndIncrement());
resourceQueue.put(product);
System.out.println("生产者" + Thread.currentThread().getName()
+ "生产资源:" + product.id + ";当前资源池有" + resourceQueue.size() +
"个资源");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
private class Consuner implements Runnable {
@Override
public void run() {
while (true) {
try {
Product product = resourceQueue.take();
//模拟服务器处理过程
Thread.sleep(500);
System.out.p