In the Java multithreaded application, the queue usage is very high, most of the production consumption model's preferred data structure is the queue (FIFO). Java provides a thread-safe queue that can be divided into blocking queues and non-blocking queues, where a typical example of a blocking queue is blockingqueue, a typical example of a nonblocking queue is concurrentlinkedqueue, In practical application, we should choose the blocking queue or non-blocking queue according to the actual need.
Note: What is thread safety? This must be clear first. Thread safety means that multithreaded access to the same code does not produce indeterminate results.
Parallelism and concurrency differences
1, parallel refers to the two at the same time to carry out a thing, such as running, two people are constantly running forward;
2, concurrency refers to the situation of limited resources, the two alternate use of resources, such as a section of the road (single-core CPU resources) at the same time only one person, a go after a period, to b,b used to continue to give a, alternating use, the purpose is to improve efficiency
Linkedblockingqueue
As the linkedblockingqueue implementation is thread-safe, realize the first-out and other characteristics, is the preferred producer of consumers , Linkedblockingqueue can specify the capacity, can also be unspecified, not specified, The default maximum is Integer.max_value, which mainly uses the put and take method, the put method is blocked when the queue is full until a queue member is consumed, the take method is blocked when the queue is empty until a queue member is put in.
Package Cn.thread;import Java.util.concurrent.blockingqueue;import Java.util.concurrent.executorservice;import Java.util.concurrent.executors;import java.util.concurrent.linkedblockingqueue;/** * Multithreaded simulation for producer/Consumer models * * @author 林计钦 * @version 1.0 2013-7-25 pm 05:23:11 */public class BlockingQueueTest2 {/** * * define basket for Apple * */Publ IC class Basket {//basket, capable of accommodating 3 apples blockingqueue<string> basket = new Linkedblockingqueue<string> ( 3); produce apples, put baskets public void produce () throws Interruptedexception {//Put method into an apple, if basket full, wait until basket has position Basket.put ("an apple"); }//Consume apples, take away public String consume () throws Interruptedexception {//takes method to remove an apple, if basket is empty, Wait until basket has an apple (get and remove the head of this queue) return Basket.take (); }}//define Apple Producer class Producer implements Runnable {private String instance; Private basket basket; Public Producer (String instance,Basket basket) {this.instance = instance; This.basket = basket; public void Run () {try {while (true) {//production Apple System.out.println ("producer ready to produce apples:" + instance); Basket.produce (); System.out.println ("! Producer produces Apple finished:" + instance); Sleep 300ms Thread.Sleep (300); }} catch (Interruptedexception ex) {System.out.println ("Producer interrupted"); }}}//define Apple Consumer class Consumer implements Runnable {private String instance; Private basket basket; Public Consumer (String instance, basket basket) {this.instance = instance; This.basket = basket; public void Run () {try {while (true) {//consume Apple SYSTEM.OUT.PRINTLN ("Consumer ready to consume Apple:" + instance); System.out.println (Basket.consume ()); SYSTEM.OUT.PRINTLN ("! Consumer consumption Apple finished:" + instance); Sleep 1000ms thread.sleep (1000); }} catch (Interruptedexception ex) {System.out.println ("Consumer interrupted"); }}} public static void Main (string[] args) {BlockingQueueTest2 test = new BlockingQueueTest2 (); Build a basket of apples basket basket = test.new basket (); Executorservice service = Executors.newcachedthreadpool (); Producer Producer = Test.new Producer ("producer 001", basket); Producer producer2 = Test.new Producer ("producer 002", basket); Consumer Consumer = test.new Consumer ("Consumer 001", basket); Service.submit (producer); Service.submit (PRODUCER2); Service.submit (consumer); After the program runs 5s, all tasks stop//try {//Thread.Sleep (5);//} catch (Interruptedexception e) {// E. Printstacktrace ();//}//Service.shutdownnow (); }}
Concurrentlinkedqueue
Concurrentlinkedqueue is a secure implementation of the queue. The elements in the queue are sorted by FIFO principle. The CAS operation is used to ensure the consistency of the elements.
Linkedblockingqueue is a thread-safe blocking queue that implements the Blockingqueue interface, The Blockingqueue interface inherits from the Java.util.Queue interface and adds the take and put methods on top of this interface, both of which are blocking versions of the queue operation.
Package Cn.thread;import Java.util.concurrent.concurrentlinkedqueue;import Java.util.concurrent.CountDownLatch; Import Java.util.concurrent.executorservice;import Java.util.concurrent.executors;public class concurrentlinkedqueuetest {private static concurrentlinkedqueue<integer> queue = new Concurrentlinkedqueue<i Nteger> (); private static int count = 2; Number of threads//countdownlatch, a synchronous helper class that allows one or more threads to wait until a set of operations that are performed in another thread is completed. private static Countdownlatch latch = new Countdownlatch (count); public static void Main (string[] args) throws Interruptedexception {Long Timestart = System.currenttimemillis (); Executorservice es = Executors.newfixedthreadpool (4); Concurrentlinkedqueuetest.offer (); for (int i = 0; i < count; i++) {Es.submit (New Poll ()); } latch.await (); Causes the main thread (main) to block until Latch.countdown () is zero before continuing to execute System.out.println ("Cost time" + (System.currenttimemillis ()-Timestart ) + "MS"); Es.shutdowN (); }/** * Production */public static void offer () {for (int i = 0; i < 100000; i++) {queue . offer (i); }}/** * consumption * * @author Lin Yi-chin * @version 1.0 2013-7-25 PM 05:32:56 */static class Poll Imple ments Runnable {public void run () {//while (Queue.size () >0) {while (!queue.isempty ()) {System.out.println (Queue.poll ()); } latch.countdown (); } }}
Operation Result:
Costtime 2360ms
After switching to while (Queue.size () >0)
Operation Result:
Cost Time 46422ms
The result is so big difference, look at the next Concurrentlinkedqueue API original. Size () is to traverse the collection again, no wonder it is so slow, so try to avoid using size instead of IsEmpty ().
Summarized under, in the unit lack of performance testing, to their own programming requirements more stringent, especially in the production environment is to be cautious.
Http://www.cnblogs.com/linjiqin/archive/2013/05/30/3108188.html
Concurrent queue Concurrentlinkedqueue and blocking queue Linkedblockingqueue usage (RPM)