public class Test { private static BlockingQueue<Integer> blockingQueue = new LinkedBlockingQueue<>(10); public static void main(String[] args) { new Thread(new Producer(blockingQueue)).start(); new Thread(new Consumer(blockingQueue)).start(); }}class Producer implements Runnable { private BlockingQueue<Integer> blockingQueue; public Producer(BlockingQueue<Integer> blockingQueue) { this.blockingQueue = blockingQueue; } @SneakyThrows @Override public void run() { while (true) { Thread.sleep(50); Random random = new Random(); int i = random.nextInt(10); System.out.println("生产者生产数据" + i); blockingQueue.put(i); System.out.println(blockingQueue.size()); } }}class Consumer implements Runnable { private BlockingQueue<Integer> blockingQueue; public Consumer(BlockingQueue<Integer> blockingQueue) { this.blockingQueue = blockingQueue; } @SneakyThrows @Override public void run() { while (true) { Thread.sleep(1000); Integer i = blockingQueue.take(); System.out.println("消费者消费数据" + i); } }}