Use of the queue interface in Java _java

Source: Internet
Author: User
Tags sorts

The queue interface, which is the same level as list and set, inherits the collection interface. LinkedList implements the queue interface. The queue interface narrows access to LinkedList methods (that is, when the parameter type in the method is a queue, you can only access the method defined by the queue interface, not directly to the LinkedList method). So that only the right method can be used. Blockingqueue inherits the queue interface.

A queue is a data structure. It has two basic operations: add an element to the tail of the queue, and remove an element from the head of the queue that is, queues manage data in a first-in, first-out way, and if you try to add an element to an already-full blocking queue or remove a single one from an empty blocking queue, the thread will block. Blocking queues is a useful tool when you are working with multithreading. Worker threads can periodically save intermediate results to a blocking queue while other worker thread threads take the intermediate results out and modify them in the future. The queue automatically balances the load. If the first set of threads runs slower than the second, the second line Cheng when it waits for the result. If the first set of threads runs fast, it waits for the second set of threads to catch up. The following table shows the actions for blocking queues in jdk1.5:

Add Add a dollar cable if the queue is full, throw a Iiiegaislabeepeplian exception
Remove and return elements of the queue's head if the queue is empty, throw a nosuchelementexception exception
Element returns the elements of the queue's head if the queue is empty, a Nosuchelementexception exception is thrown
Offer an offer to add an element and return true if the queue is full, return false
Poll Remove and return the elements of the queue header if the queue is empty, return null
Peek returns the elements of the queue header if the queue is empty, returns null
Put add an element if the queue is full, block
Take the element that removes and returns the header of the queue if the queue is empty, the block

Remove, element, offer, poll, Peek actually belong to the queue interface.

Blocking queues can be grouped into the following three categories depending on how they respond: AAD, Removee, and element operations throw an exception when you try to add elements to a full queue or get elements from an empty queue. Of course, in multithreaded programs, queues can become full or empty at any time, so you may want to use an offer, poll, peek method. These methods simply give an error and do not throw an exception when the task cannot be completed.

Note: Error in poll and Peek methods returns NULL. Therefore, it is not legal to insert null values into the queue.

There are also a variety of offer and poll methods with timeouts, for example, the following call:

Boolean success = Q.offer (X,100,timeunit.milliseconds);

Attempt to insert an element into the tail of the queue within 100 milliseconds. Returns true immediately if successful, otherwise, returns False when a timeout is reached. Likewise, call:

Object head = Q.poll (timeunit.milliseconds);

If the queue header element is successfully removed within 100 milliseconds, the element is returned immediately, or null if the timeout is reached.

Finally, we have blocking operations put and take. The Put method blocks when the queue is full, and the take method blocks when the queue is empty.

The Java.ulil.concurrent package provides 4 variants of a blocking queue. By default, the capacity of the linkedblockingqueue is not capped (inaccurate, not specified, the capacity is integer.max_value, not the words are blocked when put), but you can optionally specify its maximum capacity, which is based on a linked list of queues, This queue sorts elements by FIFO (first-in first out).

Arrayblockingqueue needs to specify capacity at construction time and can choose whether fairness is required, and if the Fair parameter is set to True, the thread with the longest waiting time will be treated preferentially (in fact, by setting the Reentrantlock to True To achieve this fairness: the longest-waiting thread will operate first. In general, fairness can make you pay for performance, and use it only when you really need it. It is an array-based blocking loop queue that sorts elements by FIFO (first-in first out) principle.

Priorityblockingqueue is a priority queue, not a first-in, first-out queue. The elements are removed in order of precedence, and the queue has no upper bound (look at the source, Priorityblockingqueue is the Priorityqueue packaging, is based on the heap data structure, and priorityqueue is not limited by capacity, As with ArrayList, it is not blocked when put on a priority blocking queue. Although this queue is logically unbounded, trying to perform an add operation may cause outofmemoryerror because the resource is depleted, but if the queue is empty, the operation of the element take is blocked, so its retrieval operation take is blocked. In addition, the elements that go into the queue have a comparative capability.

Finally, Delayqueue (based on Priorityqueue) is an unbounded blocking queue that holds the delayed element, which can be extracted only when the delay expires. The head of the queue is the delayed element that is saved for the longest time after the delay expires. If the delay has not expired, the queue has no head and poll will return NULL. When an element's Getdelay (Timeunit.nanoseconds) method returns a value less than or equal to zero, the expiration occurs and poll removes the element. Null element is not allowed for this queue. The following is a delay interface:

Java code

Public interface delayed extends Comparable<delayed> { 
   long getdelay (timeunit unit); 
} 

The elements that are put into the delayqueue will also implement the CompareTo method, which delayqueue use to sort the elements.

The following example shows how to use a blocking queue to control the set of threads. The program searches for all files in a directory and all of its subdirectories, printing out a list of files that contain the specified keywords. As you can see from the example below, the obvious advantage of using blocking queues is that there is no need for additional synchronization for multithreaded operations in common queues, and that queues automatically balance the load, which means that the processing on both sides of the line (production and consumption) is quickly blocked off, thus reducing the processing speed gap on both sides. The following is a specific implementation:

Java code

public class Blockingqueuetest {public static void main (string[] args) {Scanner in = new Scanner (system.in); 
    System.out.print ("Enter base directory (e.g./usr/local/jdk5.0/src):"); 
    String directory = In.nextline (); 
    System.out.print ("Enter keyword (e.g. volatile):"); 
 
    String keyword = in.nextline (); Final int file_queue_size = 10;//blocking Queue Size final int search_threads = 100;//keyword search thread number//Arrayblockingqueue based resistance 
 
    Plug queues blockingqueue<file> queue = new arrayblockingqueue<file> (file_queue_size); 
    Start only one thread to search the directory Fileenumerationtask enumerator = new Fileenumerationtask (queue, new File); 
     
    New Thread (Enumerator). Start (); Start 100 threads to search the file for the specified keyword for (int i = 1; I <= search_threads i++) New Thread (new searchtask queue, keyword 
  ). Start (); The class Fileenumerationtask implements Runnable {//Dummy metafile object, placed at the end of the blocking queue, is used to indicate that the file has been traversed public static file DUMMY = new F Ile""); 
  Private blockingqueue<file> queue; 
 
  Private File startingdirectory; 
    Public Fileenumerationtask (blockingqueue<file> queue, File startingdirectory) {this.queue = queue; 
  This.startingdirectory = startingdirectory; 
      public void Run () {try {enumerate (startingdirectory); Queue.put (DUMMY)//Execute here to indicate that the file in the specified directory has been traversed} catch (Interruptedexception e) {}}////Set all files in the specified directory as a file object 
    Into the blocking queue public void enumerate (File directory) throws interruptedexception {file[] files = directory.listfiles (); 
      for (file file:files) {if (File.isdirectory ()) enumerate (file); 
    else//Put the elements in the tail, and if the queue is full, block queue.put (file); 
  }} class Searchtask implements Runnable {private blockingqueue<file> queue; 
 
  Private String keyword; 
    Public Searchtask (blockingqueue<file> queue, String keyword) {this.queue = queue; 
  This.keyword = keyword; } PUBlic void Run () {try {Boolean done = false; 
        while (!done) {//Remove the first Team element and block file File = Queue.take () If the queue is empty; 
          if (file = = Fileenumerationtask.dummy) {//removed and then put back in, so that other threads read it quickly end Queue.put (file); 
        Done = true; 
      else search (file); 
    } catch (IOException e) {e.printstacktrace ();  catch (Interruptedexception e) {}} public void search (file file) throws IOException {Scanner in = new 
    Scanner (new FileInputStream (file)); 
    int linenumber = 0; 
      while (In.hasnextline ()) {linenumber++; 
      String line = In.nextline (); 
    if (line.contains (keyword)) System.out.printf ("%s:%d:%s%n", File.getpath (), linenumber, line); 
  } in.close (); 
 } 
}

Original link: http://www.cnblogs.com/end/archive/2012/10/25/2738493.html

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.