在Java中,我们可以使用`ArrayBlockingQueue`来初始化一个有界队列,以下是一个简单的示例: ```java import java.util.concurrent.ArrayBlockingQueue; public class Main { public static void main(String[] args) { // 初始化一个容量为10的有界队列 ArrayBlockingQueue<String> boundedQueue = new ArrayBlockingQueue<>(10); // 添加元素到队列 try { boundedQueue.put("Element 1"); boundedQueue.put("Element 2"); // ...添加更多元素 } catch (InterruptedException e) { e.printStackTrace(); } // 从队列中获取并移除元素 try { System.out.println(boundedQueue.take()); System.out.println(boundedQueue.take()); // ...获取并移除更多元素 } catch (InterruptedException e) { e.printStackTrace(); } } } ``` 在这个例子中,我们创建了一个容量为10的`ArrayBlockingQueue`,这意味着它最多只能存储10个元素。当尝试向已满的队列中添加元素时,`put`方法将阻塞,直到队列中有空间可用。同样,当尝试从空队列中获取元素时,`take`方法也将阻塞,直到队列中有元素可获取。 [2024-01-13 18:16:10 | AI写代码神器 | 279点数解答]