Java多线程-生产者消费者例子-使用阻塞队列(BlockingQueue)实现


import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

/**
 * Created by wisgood .
 */
public class ProducerConsumerWithBlockingQueueDemo {
    public static void main(String[] args) {
        BlockingQueue<String> productFactory = new ArrayBlockingQueue(10);
        new Thread(new ProducerWithBlockingQueue(productFactory), "1号生产者").start();
        new Thread(new ConsumerWithBlockingQueue(productFactory), "1号消费者").start();
        new Thread(new ConsumerWithBlockingQueue(productFactory), "2号消费者").start();
    }
}


// 生产者
class ProducerWithBlockingQueue implements Runnable {
    private  BlockingQueue<String> productFactory;
    public ProducerWithBlockingQueue( BlockingQueue<String> productFactory) {
        this.productFactory = productFactory;
    }
    public void run() {
        int i = 0;
        while (true) {
            try {
                String product = String.valueOf(i) ;
                //只有下面1行代码会互斥访问productFactory
                productFactory.put(product);
                System.out.println("线程(" + Thread.currentThread().getName() + ")生产了一件产品:" + product + ";当前剩余商品" + productFactory.size() + "个");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            i++;
        }
    }
}

// 消费者
class ConsumerWithBlockingQueue implements Runnable {
    private  BlockingQueue<String> productFactory;
    public ConsumerWithBlockingQueue(BlockingQueue<String> productFactory) {
        this.productFactory = productFactory;
    }

    public void run() {
        while (true) {
            try {
                System.out.println("线程(" + Thread.currentThread().getName() + ")消费了一件产品:" + productFactory.take() + ";当前剩余商品" + productFactory.size() + "个");
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }
    }
}

输出结果

线程(1号消费者)消费了一件产品:0;当前剩余商品0个
线程(1号生产者)生产了一件产品:1;当前剩余商品1个
线程(2号消费者)消费了一件产品:1;当前剩余商品0个
线程(1号生产者)生产了一件产品:2;当前剩余商品1个
线程(1号消费者)消费了一件产品:2;当前剩余商品0个
线程(1号生产者)生产了一件产品:3;当前剩余商品1个
线程(2号消费者)消费了一件产品:3;当前剩余商品0个
线程(1号生产者)生产了一件产品:4;当前剩余商品1个
线程(1号消费者)消费了一件产品:4;当前剩余商品0个
线程(1号生产者)生产了一件产品:5;当前剩余商品1个
线程(2号消费者)消费了一件产品:5;当前剩余商品0个
线程(1号生产者)生产了一件产品:6;当前剩余商品1个
线程(1号消费者)消费了一件产品:6;当前剩余商品0个

文章为作者原创文章,如果对您有帮助,欢迎打赏!这里写图片描述这里写图片描述

©️2020 CSDN 皮肤主题: Age of Ai 设计师:meimeiellie 返回首页