Detailed queue --queue

Queue: basically, a queue is a first in first out (FIFO) data structure

Queue interfaces List, Set the same level, they are inherited the Collection interface. LinkedList implement the Deque interface.

Realization of Queue


1, LinkedList blocking interface is not achieved: the interface and implements java.util.Queue java.util.AbstractQueue interfaces
  built-in unblocked queues: PriorityQueue and ConcurrentLinkedQueue
  PriorityQueue ConcurrentLinkedQueue classes and two specific collection implementations added in the Collection Framework. 
  PriorityQueue class essentially maintains an ordered list. Queue is added to the elements or to locate java.util.Comparator passed to the constructor implemented in accordance in accordance with their natural ordering (which is achieved by java.util.Comparable).
  ConcurrentLinkedQueue is based on linked nodes, thread-safe queue. Concurrent access synchronization is not required. Because it adds an element at the tail of the queue and delete them from the head, so just do not need to know the size of the queue, ConcurrentLinkedQueue share access to a common set of can work very well. Collect information about the size of the queue will be very slow, you need to traverse the queue.


2, to achieve the blocking of the interface:
  the java.util.concurrent BlockingQueue added to five blocking queue class and interfaces. It is essentially a FIFO data structure with little distortion. Not immediately add or remove elements from the queue, the thread perform the operation block until there is space available or elements.
  Have five different queues provided:

  •  ArrayBlockingQueue: backed by an array of a bounded queue.
  • LinkedBlockingQueue: a link from the node supports an optional bounded queue.
  • PriorityBlockingQueue: a support unbounded priority queue by the priority heap.
  • DelayQueue: a stack supported by a priority, time-based scheduling queue.
  • SynchronousQueue: a simple mechanism to gather BlockingQueue interface (rendezvous).

3, the main method:

    Add to add one yuan cable if the queue is full, an exception is thrown a IIIegaISlabEepeplian
  Remove removes and returns the element head of the queue if the queue is empty, throw an exception NoSuchElementException
  element returns the element head of the queue if the queue is empty, an exception is thrown a NoSuchElementException
  offer add an element and returns true if the queue is full, false returns
  poll asked element is removed and returned to the head of the queue if the queue is empty, null is returned
  peek returns the element head of the queue if the queue is empty , null is returned
  put add an element if the queue is full, the blocking
  take to remove the head of the queue and returns the element if the queue is empty, blocked

4, four queue Detailed

  (1)LinkedBlockingQueue的容量是没有上限的(说的不准确,在不指定时容量为Integer.MAX_VALUE,不要然的话在put时怎么会受阻呢),但是也可以选择指定其最大容量,它是基于链表的队列,此队列按 FIFO(先进先出)排序元素。

  (2)ArrayBlockingQueue在构造时需要指定容量, 并可以选择是否需要公平性,如果公平参数被设置true,等待时间最长的线程会优先得到处理(其实就是通过将ReentrantLock设置为true来 达到这种公平性的:即等待时间最长的线程会先操作)。通常,公平性会使你在性能上付出代价,只有在的确非常需要的时候再使用它。它是基于数组的阻塞循环队 列,此队列按 FIFO(先进先出)原则对元素进行排序。

  (3)PriorityBlockingQueue是一个带优先级的 队列,而不是先进先出队列。元素按优先级顺序被移除,该队列也没有上限(看了一下源码,PriorityBlockingQueue是对 PriorityQueue的再次包装,是基于堆数据结构的,而PriorityQueue是没有容量限制的,与ArrayList一样,所以在优先阻塞 队列上put时是不会受阻的。虽然此队列逻辑上是无界的,但是由于资源被耗尽,所以试图执行添加操作可能会导致 OutOfMemoryError),但是如果队列为空,那么取元素的操作take就会阻塞,所以它的检索操作take是受阻的。另外,往入该队列中的元 素要具有比较能力。

  (4)DelayQueue(基于PriorityQueue来实现的)是一个存放Delayed 元素的无界阻塞队列,只有在延迟期满时才能从中提取元素。该队列的头部是延迟期满后保存时间最长的 Delayed 元素。如果延迟都还没有期满,则队列没有头部,并且poll将返回null。当一个元素的 getDelay(TimeUnit.NANOSECONDS) 方法返回一个小于或等于零的值时,则出现期满,poll就以移除这个元素了。此队列不允许使用 null 元素.

 

5、代码例子

 

package is.data.structure.queue;

import java.time.Duration;
import java.time.Instant;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingDeque;

/**
 * @ClassName: FruitBasket
 * @Description:
 * 水果篮子
 * @Author: Coding_wxb
 */
public class FruitBasket {
    private boolean close = false;
    BlockingQueue<Fruit> basket = new LinkedBlockingDeque<>(10);
    //存放水果
    public void storeFruit(Fruit fruit) throws InterruptedException{
        basket.put(fruit);
    }
    //取出水果
    public Fruit getFruit() throws InterruptedException{
        return basket.take();
    }
    //获取篮子中的水果数量
    public int getSize(){
        return basket.size();
    }
    //水果生产者
    class Producer implements Runnable{
        @Override
        public void run() {
            try {
                while (!close){
                    System.out.println("生产者开始生产水果:");
                    Instant start = Instant.now();
                    Fruit fruit1 = new Fruit("read","apple");
                    Fruit fruit2 = new Fruit("yellow","pear");
                    storeFruit(fruit1);
                    storeFruit(fruit2);
                    Instant end = Instant.now();
                    System.out.println("生产水果总耗时:"+Duration.between(start,end).toMillis());
                    System.out.println("生产完水果,篮子中有:"+getSize()+"个水果");
                    Thread.sleep(3000);
                }
            }catch (Throwable e){
                e.printStackTrace();
            }
        }
    }
    //水果消费者
    class Consumer implements  Runnable{

        @Override
        public void run() {
            try {
                while (!close){
                    System.out.println("消费者开始消费水果:");
                    Instant start = Instant.now();
                    Fruit fruit = getFruit();
                    System.out.println("此次消费水果为:"+fruit.toString());
                    System.out.println("生产完水果,篮子中有:"+getSize()+"个水果");
                    Instant end = Instant.now();
                    System.out.println("消费水果总耗时:"+Duration.between(start,end).toMillis());
                    Thread.sleep(3000);
                }
            }catch (Throwable e){
                e.printStackTrace();
            }
        }
    }
    public  void test(){
        ExecutorService ex = Executors.newCachedThreadPool();
        Producer producer = new Producer();
        Consumer consumer = new Consumer();
        ex.submit(producer);
        ex.submit(consumer);
        //程序运行十秒结束
        try {
            Thread.sleep(10000);
        }catch (Throwable e){
            e.printStackTrace();
        }
        ex.shutdownNow();
    }

    public static void main(String[] args) {
        FruitBasket basket = new FruitBasket();
        basket.test();
    }
    //水果类
    class Fruit{
        private String color;
        private String name;

        public Fruit(String color, String name) {
            this.color = color;
            this.name = name;
        }

        @Override
        public String toString() {
            return "Fruit{" +
                    "color='" + color + '\'' +
                    ", name='" + name + '\'' +
                    '}';
        }
    }

}

 

Guess you like

Origin www.cnblogs.com/zbbiex/p/10953062.html