Third, the use of blockingqueue implementation
Blockingqueue is also the main tool for controlling thread synchronization under Java.util.concurrent.
Blockingqueue has four specific implementation classes, depending on the needs, choose different implementation classes
1, Arrayblockingqueue: a bounded block queue supported by an array, specifying the size of the Blockingqueue, its constructor must take an int parameter to indicate its size. The objects it contains are sorted in FIFO (first in, first out) order.
2, Linkedblockingqueue: The size of the variable blockingqueue, if its constructor with a specified size parameters, the resulting blockingqueue has a size limit, if not with the size of parameters, The size of the generated blockingqueue is determined by Integer.max_value. The objects it contains are sorted in FIFO (first in, first out) order.
3. Priorityblockingqueue: Similar to Linkedblockqueue, but the sort of objects it contains is not FIFO, but is determined by the natural sort order of the object or the comparator of the constructor.
4, Synchronousqueue: Special Blockingqueue, the operation of its must be put and take alternating completion.
Linkedblockingqueue can specify the capacity, or can not specify, if not specified, the default maximum is Integer.max_value, which is mainly used in the put and take method, the put method is blocked when the queue is full until a queue member is consumed, The Take method blocks when the queue is empty until a queue member is put in.
Import Java.util.concurrent.BlockingQueue; public class Producer implements Runnable {blockingqueue<string> queue; Public Producer (blockingqueue<string> queue) {this.queue = queue; } @Override public void Run () {try {String temp = "A product, production line:" + Thread.CurrentThread (). GetName (); System.out.println ("I have made a product:" + thread.currentthread (). GetName ()); Queue.put (temp);//If the queue is full, it will block the current thread} catch (Interruptedexception e) {e.printstacktrace (); }}} import Java.util.concurrent.BlockingQueue; public class Consumer implements runnable{blockingqueue<string> queue; Public Consumer (blockingqueue<string> queue) {this.queue = queue; @Override public void Run () {try {String temp = Queue.take ();//If the queue is empty, the current thread is blocked SYSTEM.OUT.PRINTLN (temp); } catch (Interruptedexception e) {e.printstacktrace (); }}} import Java.util.concurrent.ArrayBlockingQueue; Import Java.util.concurrent.BlockingQueue; Import Java.util.concurrent.LinkedBlockingQueue; public class Test3 {public static void main (string[] args) {blockingqueue<string> queue = new Linked Blockingqueue<string> (2); blockingqueue<string> queue = new linkedblockingqueue<string> (); If not set, linkedblockingqueue default size is Integer.max_value//blockingqueue<string> queue = new Arrayblockingq Ueue<string> (2); Consumer Consumer = new Consumer (queue); Producer Producer = new Producer (queue); for (int i = 0; i < 5; i++) {New Thread (producer, "producer" + (i + 1)). Start (); New Thread (Consumer, "consumer" + (i + 1)). Start (); } } }
Blockingqueue interface, extending the queue interface
package java.util.concurrent;import java.util.Collection;import java.util.Queue;public interface BlockingQueue<E> extends Queue<E> { boolean add(E e); boolean offer(E e); void put(E e) throws InterruptedException; boolean offer(E e, long timeout, TimeUnit unit) throws InterruptedException; E take() throws InterruptedException; E poll(long timeout, TimeUnit unit) throws InterruptedException; int remainingCapacity(); boolean remove(Object o); public boolean contains(Object o); int drainTo(Collection<? super E> c); int drainTo(Collection<? super E> c, int maxElements);}
We use the take () and put (e e)
Two methods, implemented in Arrayblockingqueue
public void put(E e) throws InterruptedException { if (e == null) throw new NullPointerException(); final E[] items = this.items; final ReentrantLock lock = this.lock; lock.lockInterruptibly(); try { try { while (count == items.length) notFull.await(); } catch (InterruptedException ie) { notFull.signal(); // propagate to non-interrupted thread throw ie; } insert(e); } finally { lock.unlock(); } }
private void insert(E x) { items[putIndex] = x; putIndex = inc(putIndex); ++count; notEmpty.signal();}
public E take() throws InterruptedException { final ReentrantLock lock = this.lock; lock.lockInterruptibly(); try { try { while (count == 0) notEmpty.await(); } catch (InterruptedException ie) { notEmpty.signal(); // propagate to non-interrupted thread throw ie; } E x = extract(); return x; } finally { lock.unlock(); } }
private E extract() { final E[] items = this.items; E x = items[takeIndex]; items[takeIndex] = null; takeIndex = inc(takeIndex); --count; notFull.signal(); return x; }
It is also implemented using the await () method of lock and condition condition variables and the signal () method, which differs from the lock usage we implemented earlier:
1) Use two condition variable consume await placed above notempty, wake up in put, produce await placed above notfull, wake up in Take (), Wake is signal instead of Signalall, This will not result in a large number of wake-up competition to reduce efficiency, through the analysis of lock objects, reduce competition
Advantages: More conducive to the coordination of the production of consumer thread balance
Multithreading-producer Consumer (Blockingqueue implementation)