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();
}
}