理解并解决Java并发问题:BlockingQueue示例

原创 今天药忘吃喽~ 2024-10-10 00:06 105阅读 0赞

在Java中,BlockingQueue 是一种线程安全的队列。它可以在元素被添加到队列时阻塞当前的线程,直到队列中有足够的空间可以接受新的元素。

以下是一个使用BlockingQueue的例子:

  1. import java.util.concurrent.BlockingQueue;
  2. import java.util.concurrent.LinkedBlockingQueue;
  3. public class BlockingQueueExample {
  4. public static void main(String[] args) {
  5. // 创建一个容量为10的阻塞队列
  6. BlockingQueue<Integer> queue = new LinkedBlockingQueue<>(10);
  7. // 向队列中添加元素,会阻塞当前线程直到有足够的空间
  8. for (int i = 0; i < 20; i++) {
  9. try {
  10. queue.put(i); // 添加元素到队列
  11. System.out.println("Element " + i + " added to the queue.");
  12. } catch (InterruptedException e) {
  13. e.printStackTrace();
  14. System.out.println("Adding element to the queue interrupted.");
  15. }
  16. }
  17. // 向空队列中添加元素,会立即返回,而不会阻塞线程
  18. try {
  19. queue.put(21); // 添加元素到空队列
  20. System.out.println("Element 21 added to an empty queue.");
  21. } catch (InterruptedException e) {
  22. e.printStackTrace();
  23. System.out.println("Adding element to an empty queue interrupted.");
  24. }
  25. }
  26. }

在这个例子中,我们首先创建了一个容量为10的BlockingQueue。然后,我们尝试向队列中添加元素20次,每次都会阻塞线程直到有足够的空间(即队列中有10个元素)。

当队列为空时,我们将试图向空队列中添加元素21,这次操作会立即返回,而不会阻塞线程。

文章版权声明:注明蒲公英云原创文章,转载或复制请以超链接形式并注明出处。

发表评论

表情:
评论列表 (有 0 条评论,105人围观)

还没有评论,来说两句吧...

相关阅读

    相关 理解解决Java并发问题

    理解和解决Java并发问题主要包括以下几个方面: 1. **线程基础**: - 理解什么是线程,线程的作用以及创建线程的方式(如Thread类、Runnable接口等)