Queue of JAVA data Structures (queues) __arcinfo

Source: Internet
Author: User
Tags class definition

A new Java.util.Queue interface is added to JDK 1.5 to support common operations of queues.

public interface Queue<e>extends collection<e>

Queues provide additional insert, extract, and check operations in addition to the basic Collection operations. There are two forms of each method: one throws an exception (when the operation fails) and the other Returns a special value (null or FALSE, depending on the operation). The latter form of the insert operation is designed specifically for a capacity-constrained queue implementation, and in most implementations the insert operation does not fail.


Throw an exception Return special value
Insert Add (E) Offer (e)
Removed from Remove () Poll ()
Check Element () Peek ()

Queues usually (but not necessarily) sort the elements in FIFO (first-in first Out) way. However, the priority queue and the LIFO queue (or stack) are exceptions, which sort the elements according to the natural order of the comparator or element provided, which sorts the elements in terms of LIFO (LIFO). Regardless of the sort method used, the header of the queue is the element that is removed by calling remove () or poll (). In the FIFO queue, all new elements are inserted at the end of the queue. Other kinds of queues may use different element placement rules. Each queue implementation must specify its order attributes.

If possible, the Offer method can insert an element, otherwise it returns false. Unlike the Collection.add method, this method can only fail to add an element by throwing an unchecked exception. The Offer method is designed for normal failure situations, not exceptions, such as in a fixed (bounded) queue.

The Remove () and poll () methods can remove and return the header of the queue. Exactly which element is removed from the queue is the function of the queue sorting policy, and the policy is different in various implementations. The Remove () and poll () methods behave differently only when the queue is empty: The Remove () method throws an exception, and the poll () method returns NULL.

Element () and peek () are returned, but not removed, the header of the queue.

The Queue implementation typically does not allow the insertion of NULL elements, although some implementations, such as LinkedList, do not prohibit the insertion of NULL. Even in a null-enabled implementation, NULL should not be inserted into the queue because Null is also used as a special return value for the poll method, indicating that the queue does not contain elements.


A subclass of the queue is provided in JDK1.5, as follows

All known implementing Classes:

Abstractqueue, Arrayblockingqueue, Arraydeque, Concurrentlinkedqueue, Delayqueue, Linkedblockingdeque, Linkedblockingqueue, LinkedList, Priorityblockingqueue, Priorityqueue, Synchronousqueue


Abstractqueue class

As you can see, the Java.util.LinkedList class implements the Java.util.Queue interface, and so does abstractqueue. The Abstractqueue class implements some of the methods of the Java.util interface (so it contains abstract in its name). And Abstractqueue focuses on the implementation of Offer,poll and Peek methods. Also use some specific implementations that have been provided.


Priorityqueue class

In Priorityqueue, automatic sorting is achieved when you add elements to the queue. According to the different constructors of the priorityqueue you use, the order of the queue elements is determined either based on their natural order or through the comparator passed in by the Priorirtyqueue constructor. The following code demonstrates how to use the Pirorityqueue class. At the front of the queue is the string "Alabama"-because the elements are arranged in a natural order in Priorityqueue (in this case, in alphabetical order).


priorityqueue<string> priorityqueue = new priorityqueue<string> ();
Priorityqueue.offer ("Texas");
Priorityqueue.offer ("Alabama");
Priorityqueue.offer ("California");
Priorityqueue.offer ("Rhode Island");
int queuesize = Priorityqueue.size ();
for (int i =0; i< queuesize; i++)
{
System.out.println (Priorityqueue.poll ());
}
The results of the implementation are as follows:


Alabama
California
Rhode Island
Texas


The queue items are arranged in natural order-alphabetical order.
As mentioned above, you can create your own comparator class and provide it to pirorityqueue. So, you can define your own sort of way. This method can be found in the Priorityqueuecomparatorusageexample class, where a helper class named state is used. As you can see below, in the class definition, state simply contains a name and a population.


private String name;
private int population;


Public state (String name, int population)
{
Super ();
THIS.name = name;
This.population = population;
}

Public String GetName ()
{
return this.name;
}

public int getpopulation ()
{
return this.population;
}
Public String toString ()
{
return GetName () + "-" + getpopulation ();
}


In Priorityqueuecomparatorusageexample, the queue uses a Java.util.Comparator custom implementation to define the order of arrangement (as follows).


Priorityqueue<state> Priorityqueue =
New Priorityqueue (6, New comparator<state> ()
{
public int Compare (state A, State B)
{
System.out.println ("comparing populations");
int populationa = A.getpopulation ();
int populationb = B.getpopulation ();
if (Populationb>populationa)
return 1;
else if (Populationb<populationa)
return-1;
Else
return 0;
}
}
);
After the Priorityqueuecomparatorusageexample class is executed, the state object added to the queue is emitted (from low to high) according to the number of the population.



Block Queue

A queue is usually limited to a given size. So far, you've seen through the implementation of the queue that using the offer or Add method Enqueue queue (with remove or poll to dequeue queue) is assumed that if the queue does not provide add or remove operations, then you do not have to wait for the program to execute. The Java.util.concurrent.BlockingQueue interface implements blocking. It adds a put and take method. It may be more useful to cite an example.


Use the original Producer/consumer relationship to assume that your producer writes a queue (more specifically a blockingqueue). You have some consumer that are being read from the queue, and in an orderly fashion, which way is what you want to see. Basically, each consumer needs to wait before it and is allowed to extract the project's previous consumer from the queue. Build this structure with your program, sir. A producer thread is used to write data to a queue, and then generate some consumer threads to read data from the same queue. Note that threads block another thread until the current thread finishes fetching an item from the queue.


The following code shows the process of writing Blockingqueue class producer. Note that the object in the Run method (you have the responsibility to implement because you inherited thread) is placed in the blockingqueue after waiting for a random amount of time (ranging from 100 to 500 milliseconds). The objects placed in the queue are just strings that contain the time when the message was generated.


The actual work of adding an object is implemented by the following statement:
Blockingqueue.put ("enqueued at:" + time)


The Put method throws Interruptedexception, so the put operation needs to be surrounded by try...catch blocks to catch thrown exceptions (see Listing 1).


The message is extracted from the producer by the consumer object, which also inherits from the thread object and therefore implements the Run method (see Listing 2).


The consumer class is designed to resemble the producer class. Instead of putting messages in Blockingqueue, the consumer class uses the Take method to remove (that is, dequeue) messages from the queue. As mentioned earlier, this needs to wait until something really exists in the queue. If the producer thread stops placing (that is, the Enqueue) object into the queue, consumer waits until the project for the queue is valid. The Testblockingqueue class, shown below, produces four consumer threads that attempt to extract objects from the Blockingqueue.


Import Java.util.concurrent.BlockingQueue;
Import Java.util.concurrent.LinkedBlockingQueue;


public class Testblockingqueue
{
public static void Main (String args[])
{
blockingqueue<string> blockingqueue = new linkedblockingqueue<string> ();
Producer Producer = new Producer (Blockingqueue, System.out);
Consumer Consumera = new Consumer ("Consumera", Blockingqueue, System.out);
Consumer Consumerb = new Consumer ("Consumerb", Blockingqueue, System.out);
Consumer Consumerc = new Consumer ("Consumerc", Blockingqueue, System.out);
Consumer consumerd = new Consumer ("Consumerd", Blockingqueue, System.out);
Producer.start ();
Consumera.start ();
Consumerb.start ();
Consumerc.start ();
Consumerd.start ();
}
}

Figure 1. Consumer Threads:these Threads dequeue messages from the "Blockingqueue in" order "you spawned them."
The following line creates the Blockingqueue:


Blockingqueue<string> Blockingqueue
= new Linkedblockingqueue<string> ();
Note that it uses the Blockingqueue linkedblockingqueue implementation. This is because Blockingqueue is an abstract class and you cannot instantiate it directly. You can also use the Arrayblockingqueuequeue type. Arrayblockingqueue uses an array as its storage device, while Linkedblockingqueue uses a linkedlist. The capacity of the arrayblockingqueue is fixed. For Linkedblockingqueue, the maximum value can be specified, and the default is borderless. This example code uses a borderless approach.


During the execution of a class, the object is read sequentially from the queue (see the following example). In fact, a consumer thread blocks other threads that access blockingqueue until it can take an object out of the queue.



Delayqueue-I am/is not incomplete

In some cases, objects stored in the queue will need to be placed in another queue for a period of time before they are ready to be removed. At this point you can use the Java.util.concurrent.DelayQueue class, he implements the class Blockingqueue interface. Delayqueue requires the queue object to reside on the queue for a specified amount of time.


I would like to confirm that it's a realistic example (which may be very much desired by you) is about muffins (muffins). Oh, muffin objects (like the java-we're talking about don't have coffee pun intended). Suppose you have a delayqueue and put some muffin objects in it. The Muffin object (shown below) must implement the Java.util.concurrent.Delayed interface so that it can be placed in Delayqueue. This interface requires the Muffin object to implement the Getdelay method (shown below). The Getdelay method, in effect, declares how long it is to keep the object in Delayqueue. When the value returned by the method changes to 0 or less than 0 o'clock, the object is ready (or, in this case, baked) and allowed to be removed (see Listing 3).


The Muffin class also implements the CompareTo (java.util.concurrent.Delayed) method. Because the delayed interface inherits from the Java.lang.Comparable class, this limits the bakecompletion time that you want to implement the muffin object by convention.


Since you don't really want to eat muffin that are not fully baked, it is necessary to place the muffin in the Delayqueue for the recommended baking time. Listing 4, taken from the Delayqueueusageexample class, shows Enqueue and dequeue muffin objects from Delayqueue.


As you can see, the baking time for the muffin object is set using its constructor (the constructor expects the baking time to be in seconds).


As mentioned before, the Muffin object is not allowed to be taken out of the delayqueue until his delay time (also called baking time) is extended. The element is taken out of the queue based on the earliest delay time. In this case, if you have some muffin objects that have already been baked, they will be taken out as long as they have been waiting (in other words, the first baked muffin will be removed before the newly baked muffin).


Synchronousqueue

In Java 1.5, another blocking queue implementation is synchronousqueue. Interestingly enough, the queue has no intrinsic capacity. This is intentional, because the queue is intended for delivery purposes. This means that in a synchronous queue structure, the put request must wait for the take request from another thread to the synchronousqueue. Also, a take request must wait for a put request from another thread to the synchronousqueue. Use the program to sample this concept, see sample code. Similar to the Linkedblockingqueue example in front, it contains a consumer (synchconsumer), see Listing 5.


The code in Listing 5 uses the poll (long Timeout,timeunit unit) method of the Synchronousqueue class. This method allows the poll process to wait a specified time before it is tired of waiting for another consuming thread to write Synchronousqueue (20 seconds in this case).


Producer (Synchproducer) in Listing 6 uses a similar offer (E o,long timeout, Timeunit unit) method to place objects into synchronousqueue. Use this method to allow a period of time (10 seconds in this case) to wait until you are tired of waiting for another thread to read the Synchronousqueue.


Testsynchqueue shows the actions of producer and consumer:


Import Java.util.concurrent.SynchronousQueue;
Import Java.util.concurrent.LinkedBlockingQueue;


public class Testsynchqueue
{
public static void Main (String args[])
{
synchronousqueue<string> synchqueue = new synchronousqueue<string> ();
Synchproducer producer = new Synchproducer ("Producera", Synchqueue, System.out);
Synchconsumer Consumera = new Synchconsumer ("Consumera", Synchqueue, System.out);
Consumera.start ();
Producer.start ();
}
}
When trying to understand the concepts behind synchronousqueue, keep in mind where the queue is usually used. In Javadoc, the synchronization queue indicates:


"They [synchronous queue] is suitable for delivery design, where objects running in one thread must synchronize with objects running in another thread to give it some information, time, or task. "





Related Article

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.