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 the actual application, according to the actual need to choose the blocking queue or non-blocking queue, can not store null values.
1, Blockingqueue under the two commonly used sub-class Linkedblockingqueue and Arrayblockingqueue, the inner part of the chain list and array implementation, in order to achieve the acquisition of elements and storage elements of the thread-safe blocking, Then can only use the inside thread-safe two methods put () and take () to implement, blocking means that the thread will be waiting for the card to die, the condition is that the queue has another thread to deposit or take out the data, it will be unlocked, plainly is full can not be saved, empty can not take, all have to wait, The equivalent of the queue is the warehouse, the warehouse has no goods on the production, the warehouse has goods can be consumed, lock conditions are notfull and notempty, this kind of queue for the producer consumer mode, the best before new to specify capacity size, otherwise the default isInteger.MAX_VALUE的大小。
2, Concurrentlinkedqueue non-blocking queue, it does not have put and take method, can be unlimited, and is thread-safe, n users at the same time can be guaranteed to store at the end of the team without confusion, but its size () method will not be timed to traverse, so special time, Do not use the development, if you determine whether there are elements can use the IsEmpty () method, do not use size () >0 to determine whether there is an element concurrentlinkedqueue queue.add (obj); or Queue.poll (obj); Is thread-safe, but other methods do not guarantee thread safety, such as judging isempty () so you have to lock yourself in multiple threads
Synchronized (queue) { if (!queue.isempty ()) { queue.poll (obj); } }
Concurrent queue Concurrentlinkedqueue and blocking queue Linkedblockingqueue usage