Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to operate put of LinkedBlockingQueue

Shulou Source: shulou.com Published: 2022-06-01 08:44:19 09月19日 Update

This article will explain in detail how to operate LinkedBlockingQueue put, the content of the article is of high quality, so the editor will share it for you as a reference. I hope you will have some understanding of the relevant knowledge after reading this article.

JDK provides seven blocking queues, which are commonly used to implement producers and consumers, and LinkedBlockingQueue is one of the most commonly used.

Public void put (E e) throws InterruptedException {if (e = null) throw new NullPointerException (); int c =-1; Node node = new Node (e); final ReentrantLock putLock = this.putLock; final AtomicInteger count = this.count; / / interruptible lock acquisition operation, that is, when the thread is in the Blocked state because the lock is not acquired, the thread can be interrupted and no longer wait. PutLock.lockInterruptibly (); try {/ / if the number of elements in the queue is equal to the queue capacity, that is, the queue is full, the current thread needs to wait. / / the reason for using the while loop is that after the thread is awakened, it is still necessary to determine whether the queue is full. / / that is, only if the queue is not satisfied can the current thread add the element while (count.get () = = capacity) {notFull.await ();} / / join the queue, that is, add the element enqueue (node); c = count.getAndIncrement () If (c + 1 < capacity) / / notify other producers notFull.signal ();} finally {putLock.unlock ();} if (c = = 0) / / notify consumers signalNotEmpty ();}

Summarize the process of adding operation.

1. Get putLock lock 2. If the queue is full, wait for (notFull.await ()) 3. The element joins the team 4. If the queue is not full after the current producer adds the element, notify other producers to add the element (notFull.signal ()) 5. Release putLock lock 6. If there are already elements in the queue, notify the consumer

The first thing is to acquire the lock. After getting the lock, wait if the queue is full, and add elements if the queue is dissatisfied.

After adding the element, notify other producers if the queue is not full

After adding an element, notify the consumer if the queue already has an element

On how to carry out the put operation of LinkedBlockingQueue to share here, I hope that the above content can be of some help to you, can learn more knowledge. If you think the article is good, you can share it for more people to see.

Tags: Queues elements producers threads production consumers consumption content articles more knowledge articles yes only capacity commonly used situation quantity process Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Technology Xiaomi MariaDB macOS Microsoft