Java中可以使用java.util.concurrent
包下的BlockingQueue
接口来实现阻塞队列。
package com.example;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
/**
* 实现阻塞队列
*
* @author tom
*/
public class BlockingQueueExample {
public static void main(String[] args) throws InterruptedException {
// 创建容量为10的阻塞队列
BlockingQueue<Integer> queue = new ArrayBlockingQueue<>(10);
// 生产者线程向队列添加元素
Thread producerThread = new Thread(() -> {
try {
for (int i = 0; i < 20; i++) {
queue.put(i);
System.out.println("Producer adds element " + i);
Thread.sleep(500);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
});
// 消费者线程从队列取出并处理元素
Thread consumerThread = new Thread(() -> {
while (true) {
try {
if(!queue.isEmpty()){
int element = queue.take();
System.out.println("Consumer consumes element " + element);
Thread.sleep(300);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
// 启动生产者和消费者线程
producerThread.start();
consumerThread.start();
// 等待两个线程结束
producerThread.join();
consumerThread.join();
}
}
# 程序输出
Producer adds element 0
Consumer consumes element 0
Producer adds element 1
Consumer consumes element 1
Producer adds element 2
Consumer consumes element 2
Producer adds element 3
Consumer consumes element 3
Producer adds element 4
Consumer consumes element 4
Producer adds element 5
Consumer consumes element 5
Producer adds element 6
Consumer consumes element 6
Producer adds element 7
Consumer consumes element 7
Consumer consumes element 8
Producer adds element 8
Consumer consumes element 9
Producer adds element 9
Producer adds element 10
Consumer consumes element 10
Producer adds element 11
Consumer consumes element 11
Consumer consumes element 12
Producer adds element 12
Consumer consumes element 13
Producer adds element 13
Consumer consumes element 14
Producer adds element 14
Producer adds element 15
Consumer consumes element 15
Consumer consumes element 16
Producer adds element 16
Consumer consumes element 17
Producer adds element 17
Producer adds element 18
Consumer consumes element 18
Consumer consumes element 19
Producer adds element 19