1. Java.util.concurrent-java Concurrency ToolkitJava 5 Adds a new package to the Java platform, the Java.util.concurrent package. This package contains a series of classes that make Java's concurrent programming easier and simpler. Before the package is added, you need to implement your own tool classes yourself.
In this article I will take you one by one to know these classes in the Java.util.concurrent package, and then you can try to use them in your project. I'm going to use Java version 6 in this article, and I'm not sure if there are any differences between this and the Java 5 version.
I'm not going to explain the core issue of Java concurrency-the rationale behind it-that is, if you're interested in those things, refer to the Java Concurrency Guide.
semi-finished
This article is largely a "semi-finished", so be patient when you discover some of the missing classes or interfaces. I'll add them in when I'm free.
2. Block Queue Blockingqueue the Blockingqueue interface in the Java.util.concurrent package represents a line Shuo the queue where the instance is placed and fetched. In this section I will show you how to use this blockingqueue.
This section does not discuss how to implement one of your own blockingqueue in Java. If you are interested in that, refer to the Java concurrency guide
blockingqueue usage blockingqueue is typically used for one thread production object, while another thread consumes the scene of those objects. The following diagram illustrates this principle:
A thread goes inside, and another thread takes a blockingqueue from the inside.
A thread will continue to produce new objects and insert them into the queue until the queue reaches the critical point it can hold. In other words, it is limited. If the blocking queue reaches its critical point, the thread responsible for production will block when a new object is inserted inside. It will remain blocked until the consuming thread takes an object away from the queue. The
thread responsible for consumption will always take objects out of the blocking queue. If a consumer thread attempts to extract an object from an empty queue, the consuming thread will be stuck until a line thread throws an object into the queue. The
Blockingqueue method Blockingqueue has 4 different sets of methods for inserting, removing, and checking the elements in the queue. If the requested operation cannot be performed immediately, the performance of each method is different. These methods are as follows:
|
Throw exception |
specific value |
blocking |
timeout |
| Insert |
Add (o) |
Offer (O) |
Put (o) |
Offer (o, timeout, timeunit) |
| Removed from |
Remove (o) |
Poll (o) |
Take (o) |
Poll (timeout, timeunit) |
| Check |
Element (O) |
Peek (o) |
|
|
Four different sets of behavioral patterns are explained:
Throw Exception: Throws an exception if the attempted operation cannot be executed immediately.
Specific Values: Returns a specific value (often true/false) if the attempted operation cannot be performed immediately.
Blocking: If the attempted operation cannot be executed immediately, the method call will block until it is able to execute.
timed out: If the attempted operation cannot be executed immediately, the method call will block until it can execute, but the wait time will not exceed the given value. Returns a specific value to tell if the operation was successful (typically True/false). Unable to insert null into a blockingqueue. If you try to insert a null,blockingqueue it will throw a nullpointerexception.
You can access all the elements in the blockingqueue, not just the start and end elements. For example, you put an object in the queue to wait for processing, but your app wants to cancel it out. Then you can call the Remove (O) method to remove the specific object in the queue. But this is not very efficient (the translator notes: queue-based data structures, to get other objects in addition to the beginning or end of the efficiency is not too high), so you try not to use this kind of method, unless you really have to do that.
the realization of BlockingqueueBlockingqueue is an interface, you need to use one of its implementations to use Blockingqueue. The java.util.concurrent has the following implementation of the Blockingqueue interface (Java 6):
Arrayblockingqueue delayqueue linkedblockingqueue priorityblockingqueue synchronousqueue
examples of using blockingqueue in JavaHere is an example of using Blockingqueue in Java. This example uses the Arrayblockingqueue implementation of the Blockingqueue interface.
First, the Blockingqueueexample class launches a Producer and a Consumer in two separate threads respectively. Producer injects strings into a shared blockingqueue, and Consumer takes them out from there.
[Java]View Plain copy print? public class Blockingqueueexample {
public static void Main (string[] args) throws Exception {
Blockingqueue queue = new Arrayblockingqueue (1024);
Producer Producer = new Producer (queue); Consumer Consumer = new Consumer (queue);
New Thread (producer). Start (); New Thread (consumer). Start ();
Thread.Sleep (4000); } }
public class Blockingqueueexample {public
static void Main (string[] args) throws Exception {
Blockingqueue queue = new Arrayblockingqueue (1024x768);
Producer Producer = new Producer (queue);
Consumer Consumer = new Consumer (queue);
New Thread (producer). Start ();
New Thread (consumer). Start ();
Thread.Sleep (4000);
}
}
The following is the Producer class. Notice how it sleeps for one second each time the put () is called. This causes Consumer to block while waiting for objects in the queue.
[Java]View Plain copy print? public class Producer implements runnable{
protected Blockingqueue queue = null;
Public Producer (Blockingqueue queue) {this.queue = queue;}
public void Run () {try {queue.put ("1"); Thread.Sleep (1000); Queue.put ("2"); Thread.Sleep (1000); Queue.put ("3"); } catch (Interruptedexception e) {e.printstacktrace ();}} }
public class Producer implements runnable{
protected blockingqueue queue = null;
Public Producer (Blockingqueue queue) {
this.queue = queue;
}
public void Run () {
try {
queue.put ("1");
Thread.Sleep (+);
Queue.put ("2");
Thread.Sleep (+);
Queue.put ("3");
} catch (Interruptedexception e) {
e.printstacktrace ();}}
}
The following is the Consumer class. It simply extracts the objects from the queue and prints them to the System.out.
[Java]View Plain copy print? public class Consumer implements runnable{
protected Blockingqueue queue = null;
Public Consumer (Blockingqueue queue) {this.queue = queue;}
public void Run () {try {System.out.println (Queue.take ()); System.out.println (Queue.take ()); System.out.println (Queue.take ()); } catch (Interruptedexception e) {e.printstacktrace ();}} }
public class Consumer implements runnable{
protected blockingqueue queue = null;
Public Consumer (Blockingqueue queue) {
this.queue = queue;
}
public void Run () {
try {
System.out.println (Queue.take ());
System.out.println (Queue.take ());
System.out.println (Queue.take ());
} catch (Interruptedexception e) {
e.printstacktrace ();}}
}
3. Array blocking queue Arrayblockingqueue Arrayblockingqueue class implements the Blockingqueue interface.
Arrayblockingqueue is a bounded blocking queue whose internal implementation is to place objects in an array. Bounded means that it is not able to store an infinite number of elements. It has a maximum number of elements that can be stored at the same time. You can set this limit at the time you initialize it, but you won't be able to modify it later (the translator notes: Because it is an array-based implementation, it has the properties of the array: once initialized, the size cannot be modified).
The Arrayblockingqueue internally stores the elements in FIFO (first-in, in-place) order. The head element in the queue is the longest one in all elements, and the tail element is the shortest.
The following is an example of initializing a arrayblockingqueue when it is used:
[Java] view plain copy print? Blockingqueue queue = new Arrayblockingqueue (1024);
Queue.put ("1");
Object object = Queue.take ();
Blockingqueue queue = new Arrayblockingqueue (1024x768);
Queue.put ("1");
Object object = Queue.take ();
The following is an example of a blockingqueue that uses Java generics. Notice how the String element is put in and extracted:
[Java]View Plain copy print? blockingqueue<string> queue = new arrayblockingqueue<string> (1024);
Queue.put ("1");
String string = Queue.take ();
blockingqueue<string> queue = new arrayblockingqueue<string> (1024x768);
Queue.put ("1");
String string = Queue.take ();
4. Delay Queue Delayqueue Delayqueue implements the Blockingqueue interface.
The delayqueue holds the element until a specific delay expires. The injected element must implement the Java.util.concurrent.Delayed interface, which defines:
[Java] view plain copy print? Public interface Delayed extends comparable<delayed< {
Public long Getdelay (Timeunit timeunit);
}
Public interface Delayed extends comparable<delayed< {public
long Getdelay (Timeunit timeunit);
}
Delayqueue will release the element after the time period of the value returned by the Getdelay () method of each element. If the return is 0 or a negative value, the delay will be considered expired and the element will be freed when the next take of Delayqueue is called.
The Getdelay instance passed to the Getdelay method is an enumeration type that indicates the period of time that will be deferred. The Timeunit enumeration will take the following values:
[Java]View Plain copy print? Days HOURS MINUTES SECONDS MILLISECONDS microseconds nanoseconds
Days
HOURS
MINUTES
SECONDS
MILLISECONDS
microseconds
nanoseconds
As you can see, the Delayed interface also inherits the Java.lang.Comparable interface, which means that there is a comparison between the Delayed objects. This may be useful in ordering elements in the Delayqueue queue, so they can be released in an orderly fashion based on their expiration time.
Here's an example of using Delayqueue:
[Java]View Plain copy print? public class Delayqueueexample {
public static void Main (string[] args) {delayqueue queue = new Delayqueue ();
Delayed element1 = new Delayedelement ();
Queue.put (ELEMENT1);
Delayed Element2 = Queue.take (); } }
public class Delayqueueexample {public
static void Main (string[] args) {
delayqueue queue = new Delayqueue ();
delayed element1 = new Delayedelement ();
Queue.put (element1);
Delayed Element2 = Queue.take ();
}
}
Delayedelement is the implementation class of a delayedelement interface that I created, which is not in the Java.util.concurrent package. You need to create your own implementation of the Delayed interface to use the Delayqueue class yourself.
5. The chain blocking queue Linkedblockingqueue Linkedblockingqueue class implements the Blockingqueue interface.
Inside the linkedblockingqueue, its elements are stored in a chain structure (linked nodes). This chain structure can be selected with an upper limit if required. If no upper bounds are defined, Integer.max_value is used as the upper limit.
The Linkedblockingqueue internally stores the elements in FIFO (first-in, in-place) order. The head element in the queue is the longest one in all elements, and the tail element is the shortest.
The following is the initialization of linkedblockingqueue and the use of sample code:
[Java] view plain copy print? blockingqueue<string> unbounded = new linkedblockingqueue<string> (); blockingqueue<string> bounded = new Linkedbl