@Testpublic void test() throws InterruptedException {// 创建一个阻塞队列// 编写1个生产者-3个消费者的模型BlockingQueue<String> queue = new ArrayBlockingQueue<>(3);// 1个生产者new Thread(() -> {// 生产20个元素for (int i = 0; i < 20; i++) {try {// 生产元素如果满了阻塞等待queue.put("元素_"+i);System.out.println("生产者生产元素: " + i);Thread.sleep(1000);} catch (InterruptedException e) {throw new RuntimeException(e);}}}).start();// 3个消费者for (int i = 0; i < 3; i++) {final int index = i;new Thread(() -> {while (true){try {// 消费元素,如果队列为空阻塞等待System.out.println("消费者"+index+"消费元素: " + queue.take());Thread.sleep(5000);// 延迟一下} catch (InterruptedException e) {throw new RuntimeException(e);}}}).start();}Thread.sleep(40000);// 延迟30s,防止程序提前结束,导致消费者没有消费完毕}
打印如下:
生产者生产元素: 0
消费者0消费元素: 元素_0
生产者生产元素: 1
消费者2消费元素: 元素_1
~
~
~
生产者生产元素: 19
消费者1消费元素: 元素_17
消费者0消费元素: 元素_18
消费者2消费元素: 元素_19