The use of Java concurrency Blockingqueue

Source: Internet
Author: User

The use of Java concurrency Blockingqueue

I. INTRODUCTION

  Some time ago to see some friends on the Internet sent an interview problem, the main idea is: There are two threads A, a, a thread every 200ms to generate a random number between [0,100], B thread every 2S to print out a thread generated by the increment random number. In fact, the author believes that the study of the knowledge point is this blog to introduce you to the Blockingqueue this interface, for the topic I think the interview is only the interviewer on this class whether master, there is no other.

Two. Use of Blockingqueue

 Blockingqueue is a blocking queue in which the user can set an initial capacity (that is, the maximum number of data that can be placed in that queue). Since it is the queue, then it must be ordered, and we can call the given API to get the order of the values in that queue in turn. About API after solving the above interview problem, I will pick some important and very commonly used to give the reader a detailed description.

The following code example is the author to solve the problem of the code, if the reader has a better solution, welcome to the author's message, if there are errors, please advise.

 Public classBlockingqueuetest {/*** Instantiate a queue with a capacity of ten in the queue*/    Private StaticBlockingqueue<integer> Blockingqueue =NewLinkedblockingqueue<> (10);  Public Static voidMain (string[] args) {Scheduledexecutorservice product= Executors.newscheduledthreadpool (1); Random Random=NewRandom (); Product.scheduleatfixedrate (()- {            intValue = Random.nextint (101); Try{Blockingqueue.offer (value); //The Offer () method is the tail setting value of the net queue}Catch(Exception ex) {ex.printstacktrace (); }        }, 0, Timeunit.milliseconds);//thread execution every 100 milliseconds        NewThread (() {             while(true){                Try{Thread.Sleep (2000); System.out.println ("Start to take value"); List<Integer> list =NewLinkedlist<>();  Blockingqueue.drainto (list); //Drainto () removes all values from the queue and assigns values to the corresponding collectionList.foreach (system.out::p rintln); } Catch(interruptedexception e) {e.printstacktrace ();    }}). Start (); }}

Three. Introduction to API in Blockingqueue

Offer (e): sets the given element to the queue and returns false if the setting returns true successfully. The value of E cannot be null, otherwise a null pointer exception is thrown.

Offer (e E, long timeout, timeunit unit): Sets the given element to the queue for a given time and returns false if the setting returns true successfully.

Add (E): Sets the given element to the queue, or throws an exception if the setting returns true successfully. The offer () method is recommended if you are setting values in a queue that has a length limit.

put (e): Sets the element to the queue, and if there is no extra space in the queue, the method will block until there is extra space in the queue.

Take (): Gets the value from the queue, and if there is no value in the queue, the thread blocks until there is a value in the queue, and the method obtains the value.

Poll (long timeout, timeunit unit): Gets the value from the queue at a given time, if it is not fetched to throw an exception.

remainingcapacity (): Gets the remaining space in the queue.

Remove (Object o): Removes the specified value from the queue.

contains (Object o): Determines whether the value is in the queue.

Drainto (Collection c): Remove all the values in the queue, and set the concurrency to the given collection.

The use of Java concurrency Blockingqueue

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.