Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to implement blocking queue with BlockingQueue

2025-02-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

This article will explain in detail how to use BlockingQueue to achieve blocking queue, 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.

Package com.shi.queue;import java.util.concurrent.ArrayBlockingQueue;import java.util.concurrent.BlockingQueue;import java.util.concurrent.TimeUnit;/** * blocking queue * @ author shiye * * / public class TestBlockQueue {public static void main (String [] args) throws InterruptedException {/ / define a blocking queue of length 3 BlockingQueue blockingQueue = new ArrayBlockingQueue (3) System.out.println ("- case where an exception is thrown -"); / / blockingQueue.add ("aa"); / / blockingQueue.add ("bb"); / / blockingQueue.add ("cc") / / blockingQueue.add ("dd"); / / if the queue is full of Exception java.lang.IllegalStateException: Queue full / / System.out.println (blockingQueue.element ()); / / check the queue header information: aa / / blockingQueue.remove (); / / blockingQueue.remove (); / / blockingQueue.remove () / / blockingQueue.remove (); / / if the queue is listed as empty Exception java.util.NoSuchElementException / / System.out.println (blockingQueue.element ()) / / if the queue is listed as empty Exception java.util.NoSuchElementException System.out.println ("- returns true/false--"); / / System.out.println (blockingQueue.offer ("11")) / / insert queue true// System.out.println (blockingQueue.offer ("22")); / / insert queue true// System.out.println (blockingQueue.offer ("33")); / / insert queue true// System.out.println (blockingQueue.offer ("44")) / / insert queue false// System.out.println (blockingQueue.peek ()); / / check queue header element 11max / / System.out.println (blockingQueue.poll ()); / / output queue 11max / System.out.println (blockingQueue.poll ()) / / output queue 22max / System.out.println (blockingQueue.poll ()); / / output queue 33max / System.out.println (blockingQueue.poll ()) / / output queue null System.out.println ("- queue blocking waiting -"); / / blockingQueue.put ("zhangsan"); / / blockingQueue.put ("lisi"); / / blockingQueue.put ("wangwu") / blockingQueue.put ("shiye"); / / the thread has been waiting to close / blockingQueue.take (); / / blockingQueue.take () / / the thread has been waiting for the System.out.println to fail to respond ("- the queue waits for a certain amount of time and then exits -"); System.out.println (blockingQueue.offer ("aa", 2, TimeUnit.SECONDS)) / / true System.out.println (blockingQueue.offer ("aa", 2, TimeUnit.SECONDS)); / / true System.out.println (blockingQueue.offer ("aa", 2, TimeUnit.SECONDS)); / / true System.out.println (blockingQueue.offer ("aa", 2, TimeUnit.SECONDS)); / / false waits for 2 seconds before exiting}}

SynchronousQueue

Package com.shi.queue;import java.util.concurrent.BlockingQueue;import java.util.concurrent.SynchronousQueue;/** * A queue that does not store data, that is, produce a queue that consumes one by one * @ author shiye * * result: AA stores 1. BB get 1 AA storage 2... BB get 2 AA storage 3... BB get 3 * / public class TestSynchroniousQueue {public static void main (String [] args) {BlockingQueue blockingQueue = new SynchronousQueue (); new Thread (()-> {try {System.out.println (Thread.currentThread (). GetName () + "\ t store 1...") BlockingQueue.put ("1"); System.out.println (Thread.currentThread (). GetName () + "\ t store 2..."); blockingQueue.put ("2") System.out.println (Thread.currentThread (). GetName () + "\ t store 3..."); blockingQueue.put ("3");} catch (InterruptedException e) {e.printStackTrace () }, "AA") .start (); new Thread (()-> {try {Thread.sleep (5000)) / / sleep for 5 seconds System.out.println (Thread.currentThread (). GetName () + "\ t get" + blockingQueue.take ()); Thread.sleep (5000) / / sleep for 5 seconds System.out.println (Thread.currentThread (). GetName () + "\ t get" + blockingQueue.take ()); Thread.sleep (5000) / / sleep for 5 seconds System.out.println (Thread.currentThread (). GetName () + "\ t get" + blockingQueue.take ());} catch (InterruptedException e) {e.printStackTrace ();}}, "BB") .start () }}

Comprehensive case (using blocking queues to implement producer-consumer problems)

Package com.shi.queue;import java.util.concurrent.ArrayBlockingQueue;import java.util.concurrent.BlockingQueue;import java.util.concurrent.CountDownLatch;import java.util.concurrent.TimeUnit;import java.util.concurrent.atomic.AtomicInteger / * * implementing producer-consumer problems by blocking queues * @ author shiye * techniques used: * countDownLatch: locking * volatile spin locking * AtomicInteger Atomic Integer * BlockingQueue blocking queue * * / public class TestProducterAndConsumterByQueue {public static void main (String [] args) throws InterruptedException {/ / locking Final CountDownLatch countDownLatch = new CountDownLatch (11) Check check = new Check (new ArrayBlockingQueue (3)); / / create thread production (start 10 threads to produce) for (int I = 0; I

< 10; i++) { new Thread(()->

{System.out.println (Thread.currentThread (). GetName () + "\ t producer startup."); try {check.productor ("aaa") } catch (InterruptedException e) {e.printStackTrace ();} countDownLatch.countDown (); / / the number of threads minus one}, "AA-" + I) .start () } / / create a thread to consume new Thread (()-> {System.out.println (Thread.currentThread (). GetName () + "\ t consumer startup.") Try {check.consumter ();} catch (InterruptedException e) {e.printStackTrace ();} countDownLatch.countDown () / / reduce the number of threads by one}, "BB") .start (); Thread.sleep (5000); / / wait 5 seconds to stop check.stop (); countDownLatch.await () / wait for all the above threads to finish executing before checking the product quantity System.out.println ("after 5s, the thread stops and the total production is:" + check.getTotle () + "piece product");}} / / the shop assistant class Check {private volatile boolean FLAG = true;// flag bit private AtomicInteger atomicInteger = new AtomicInteger (); / / the variable private BlockingQueue blockingQueue = null for the total number of products / / define a blocking queue public Check (BlockingQueue blockingQueue) {this.blockingQueue = blockingQueue; System.out.println ("create one" + blockingQueue.getClass () .getName () + "instance") } / / producer public void productor (String num) throws InterruptedException {while (FLAG) {System.out.println (Thread.currentThread (). GetName () + "\ t producer production data:" + num + "to queue."); blockingQueue.offer (num,2l,TimeUnit.SECONDS) / / delay inserting data into the queue by 2s. Thread.sleep (1000); / / Thread sleep 1s atomicInteger.getAndIncrement (); / / Let the total add 1}} / / Consumer public void consumter () throws InterruptedException {while (FLAG) {Object object = blockingQueue.poll (2, TimeUnit.SECONDS) / / maximum consumption delay 2s if (object! = null) {System.out.println (Thread.currentThread (). GetName () + "\ t Consumer consumption data:" + object) } / / stop public void stop () {FLAG = false;} public int getTotle () {return atomicInteger.get () }} this is the end of sharing about how to use BlockingQueue to implement blocking queues. I hope the above content can be of some help and learn more knowledge. If you think the article is good, you can share it for more people to see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report