理解并解决Java并发问题:BlockingQueue示例
在Java中,BlockingQueue
是一种线程安全的队列。它可以在元素被添加到队列时阻塞当前的线程,直到队列中有足够的空间可以接受新的元素。
以下是一个使用BlockingQueue
的例子:
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
public class BlockingQueueExample {
public static void main(String[] args) {
// 创建一个容量为10的阻塞队列
BlockingQueue<Integer> queue = new LinkedBlockingQueue<>(10);
// 向队列中添加元素,会阻塞当前线程直到有足够的空间
for (int i = 0; i < 20; i++) {
try {
queue.put(i); // 添加元素到队列
System.out.println("Element " + i + " added to the queue.");
} catch (InterruptedException e) {
e.printStackTrace();
System.out.println("Adding element to the queue interrupted.");
}
}
// 向空队列中添加元素,会立即返回,而不会阻塞线程
try {
queue.put(21); // 添加元素到空队列
System.out.println("Element 21 added to an empty queue.");
} catch (InterruptedException e) {
e.printStackTrace();
System.out.println("Adding element to an empty queue interrupted.");
}
}
}
在这个例子中,我们首先创建了一个容量为10的BlockingQueue
。然后,我们尝试向队列中添加元素20次,每次都会阻塞线程直到有足够的空间(即队列中有10个元素)。
当队列为空时,我们将试图向空队列中添加元素21,这次操作会立即返回,而不会阻塞线程。
还没有评论,来说两句吧...