public class BlockQueueTest {
public static void main(String[] args) {
BlockQueueCapacity blockQueueCapacity = new BlockQueueCapacity();
new Thread(() -> {
for (int i = 0; i < 1000; i++) {
Boolean add = blockQueueCapacity.add(i);
LockSupport.parkNanos(300000000);
if(!add){
System.out.println(i);
}
}
}).start();
ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(10);
scheduledExecutorService.scheduleAtFixedRate(new Thread(() -> {
List<Integer> integers = blockQueueCapacity.batchElement(10);
System.out.println(integers);
}), 1, 1, TimeUnit.SECONDS);
}
}
public class BlockQueueCapacity {
private transient BlockingQueue<Integer> queue = new LinkedBlockingQueue<>(100);
public Boolean add(Integer task) {
System.out.println("queue add"+task);
return queue.offer(task);
}
public List<Integer> batchElement(Integer size) {
List<Integer> result = new ArrayList<>();
for (int i = 0; i < size; i++) {
Integer element = queue.poll();
if (Objects.isNull(element)) {
return result;
} else {
result.add(element);
}
}
return result;
}
}