BlockingQueue实现生产者和消费者

生产者消费者问题
生产者生成1~100的随机整数,消费者消费这个整数并打印。
生产者有三个,每秒生成一个随机整数。
消费者有两个,每秒消费一个整数
仓库里有20个数则生产者停止生产,小于则继续生产。

Producer

public class Producer implements Runnable {

    private String name;
    private BlockingQueue queue;

    public Producer(String name, BlockingQueue queue) {
        this.name = name;
        this.queue = queue;
    }

    @Override
    public void run() {
        while (true) {
            try {
                Thread.sleep(1000);
                int value = (int)(Math.random() * 100);
                queue.put(value);
                System.out.println(name + " 生产数字 -> " + value + ",当前队列有" + queue.size() + "个数");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

Consumer

public class Consumer implements Runnable {

    String name;
    BlockingQueue queue;

    public Consumer(String name, BlockingQueue queue) {
        this.name = name;
        this.queue = queue;
    }

    @Override
    public void run() {
        try {
            int value = 0;
            while (true) {
                Thread.sleep(1000);
                value = queue.take();
                System.out.println("holylogs " + name + " 消费数字 -> " + value + ",当前队列有" + queue.size() + "个数");
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

main

// 大小为20的队列
BlockingQueue producerQueue = new LinkedBlockingQueue<>(20);

Producer producer1 = new Producer("生产1号", producerQueue);
Producer producer2 = new Producer("生产2号", producerQueue);
Producer producer3 = new Producer("生产3号", producerQueue);

Consumer consumer1 = new Consumer("消费1号", producerQueue);
Consumer consumer2 = new Consumer("消费2号", producerQueue);

// 开始producer线程进行生产
new Thread(producer1).start();
new Thread(producer2).start();
new Thread(producer3).start();

// 开始consumer线程进行消费。
new Thread(consumer1).start();
new Thread(consumer2).start();

你可能感兴趣的:(BlockingQueue实现生产者和消费者)