Java链式阻塞队列LinkedBlockQueue使用介绍

108 阅读1分钟
public class LinkedBlockQueueDemo {

    private static final int CAPACITY = 1;
    public static void main(String[] args) {
        LinkedBlockingQueue<Double> queue = new LinkedBlockingQueue<>(CAPACITY);

        // 生产者线程 生产数据
        producer(queue);
        // 消费者线程 消费数据
        consumer(queue);
    }

    private static void producer(BlockingQueue<Double> queue) {
        new Thread(() -> {
            while (true) {
                try {
                    if (queue.isEmpty()) {
                        double random = Math.random();
                        queue.put(random);
                        System.out.println("生产数据:" + random);

                        Thread.sleep(1000);
                    }
                } catch(InterruptedException e){
                    throw new RuntimeException(e);
                }
            }
        }).start();
    }

    private static void consumer(BlockingQueue<Double> queue) {
        new Thread(() -> {
            while (true) {
                try {
                    Thread.sleep(500);

                    if (queue.size() == CAPACITY) {
                        Double poll = queue.poll();
                        System.out.println("消费数据" + poll);
                    }
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }).start();
    }
}