Java多线程总结之线程安全队列Queue

  在Java多线程应用中,队列的使用率很高,多数生产消费模型的首选数据结构就是队列。Java提供的线程安全的Queue可以分为阻塞队列和非阻塞队列,其中阻塞队列的典型例子是BlockingQueue,非阻塞队列的典型例子是

ConcurrentLinkedQueue,在实际应用中要根据实际需要选用阻塞队列或者非阻塞队列。

注:什么叫线程安全?这个首先要明确。线程安全的类 ,指的是类内共享的全局变量的访问必须保证是不受多线程形式影响的。如果由于多线程的访问(比如修改、遍历、查看)而使这些变量结构被破坏或者针对这些变量操作的原子性被破坏,则这个类就不是线程安全的。

在并发的队列上jdk提供了两套实现,一个是以ConcurrentLinkedQueue为代表的高性能队列,一个是以BlockingQueue接口为代表的阻塞队列,无论在那种都继承自Queue。
今天就聊聊这两种Queue

  • BlockingQueue  阻塞算法
  • ConcurrentLinkedQueue,非阻塞算法

一、首先来看看BlockingQueue: 

Queue是什么就不需要多说了吧,一句话:队列是先进先出。相对的,栈是后进先出。如果不熟悉的话先找本基础的数据结构的书看看吧。 

BlockingQueue,顾名思义,“阻塞队列”:可以提供阻塞功能的队列。 
首先,看看BlockingQueue提供的常用方法: 

从上表可以很明显看出每个方法的作用,这个不用多说。我想说的是:

  • add(e) remove() element() 方法不会阻塞线程。当不满足约束条件时,会抛出IllegalStateException 异常。例如:当队列被元素填满后,再调用add(e),则会抛出异常。
  • offer(e) poll() peek() 方法即不会阻塞线程,也不会抛出异常。例如:当队列被元素填满后,再调用offer(e),则不会插入元素,函数返回false。
  • 要想要实现阻塞功能,需要调用put(e) take() 方法。当不满足约束条件时,会阻塞线程。
  • BlockingQueue  阻塞算法

BlockingQueue作为线程容器,可以为线程同步提供有力的保障。

BlockingQueue定义的常用方法:

     抛出异常    特殊值      阻塞       超时

插入   add(e)        offer(e)      put(e)     offer(e, time, unit)
移除   remove()    poll()         take()      poll(time, unit)
检查   element()   peek()       不可用    不可用

1、ArrayBlockingQueue

  基于数组的阻塞队列实现,在ArrayBlockingQueue内部,维护了一个定长数组,以便缓存队列中的数据对象,这是一个常用的阻塞队列,除了一个定长数组外,ArrayBlockingQueue内部还保存着两个整形变量,分别标识着队列的头部和尾部在数组中的位置。
  ArrayBlockingQueue在生产者放入数据和消费者获取数据,都是共用同一个锁对象,由此也意味着两者无法真正并行运行,这点尤其不同于LinkedBlockingQueue;按照实现原理来分析,ArrayBlockingQueue完全可以采用分离锁,从而实现生产者和消费者操作的完全并行运行。Doug Lea之所以没这样去做,也许是因为ArrayBlockingQueue的数据写入和获取操作已经足够轻巧,以至于引入独立的锁机制,除了给代码带来额外的复杂性外,其在性能上完全占不到任何便宜。 ArrayBlockingQueue和LinkedBlockingQueue间还有一个明显的不同之处在于,前者在插入或删除元素时不会产生或销毁任何额外的对象实例,而后者则会生成一个额外的Node对象。这在长时间内需要高效并发地处理大批量数据的系统中,其对于GC的影响还是存在一定的区别。而在创建ArrayBlockingQueue时,我们还可以控制对象的内部锁是否采用公平锁,默认采用非公平锁。

2、LinkedBlockingQueue

  基于链表的阻塞队列,同ArrayListBlockingQueue类似,其内部也维持着一个数据缓冲队列(该队列由一个链表构成),当生产者往队列中放入一个数据时,队列会从生产者手中获取数据,并缓存在队列内部,而生产者立即返回;只有当队列缓冲区达到最大值缓存容量时(LinkedBlockingQueue可以通过构造函数指定该值),才会阻塞生产者队列,直到消费者从队列中消费掉一份数据,生产者线程会被唤醒,反之对于消费者这端的处理也基于同样的原理。而LinkedBlockingQueue之所以能够高效的处理并发数据,还因为其对于生产者端和消费者端分别采用了独立的锁来控制数据同步,这也意味着在高并发的情况下生产者和消费者可以并行地操作队列中的数据,以此来提高整个队列的并发性能。
作为开发者,我们需要注意的是,如果构造一个LinkedBlockingQueue对象,而没有指定其容量大小,LinkedBlockingQueue会默认一个类似无限大小的容量(Integer.MAX_VALUE),这样的话,如果生产者的速度一旦大于消费者的速度,也许还没有等到队列满阻塞产生,系统内存就有可能已被消耗殆尽了。

阻塞队列:线程安全

  按 FIFO(先进先出)排序元素。队列的头部 是在队列中时间最长的元素。队列的尾部 是在队列中时间最短的元素。新元素插入到队列的尾部,并且队列检索操作会获得位于队列头部的元素。链接队列的吞吐量通常要高于基于数组的队列,但是在大多数并发应用程序中,其可预知的性能要低。

注意:

1、必须要使用take()方法在获取的时候达成阻塞结果
2、使用poll()方法将产生非阻塞效果

3、LinkedBlockingQueue实例

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;

 

public class BlockingDeque {
    //阻塞队列,FIFO
    private static LinkedBlockingQueue<Integer> concurrentLinkedQueue = new LinkedBlockingQueue<Integer>(); 

          
 public static void main(String[] args) {  
     ExecutorService executorService = Executors.newFixedThreadPool(2);  

     executorService.submit(new Producer("producer1"));  
     executorService.submit(new Producer("producer2"));  
     executorService.submit(new Producer("producer3"));  
     executorService.submit(new Consumer("consumer1"));  
     executorService.submit(new Consumer("consumer2"));  
     executorService.submit(new Consumer("consumer3"));  

 }  

 static class Producer implements Runnable {  
     private String name;  

     public Producer(String name) {  
         this.name = name;  
     }  

     public void run() {  
         for (int i = 1; i < 10; ++i) {  
             System.out.println(name+ "  生产: " + i);  
             //concurrentLinkedQueue.add(i);  
             try {
                concurrentLinkedQueue.put(i);
                Thread.sleep(200); //模拟慢速的生产,产生阻塞的效果
            } catch (InterruptedException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
             
         }  
     }  
 }  

 static class Consumer implements Runnable {  
     private String name;  

     public Consumer(String name) {  
         this.name = name;  
     }  
     public void run() {  
         for (int i = 1; i < 10; ++i) {  
             try {          
                    //必须要使用take()方法在获取的时候阻塞
                      System.out.println(name+"消费: " +  concurrentLinkedQueue.take());  
                      //使用poll()方法 将产生非阻塞效果
                      //System.out.println(name+"消费: " +  concurrentLinkedQueue.poll());  
                     
                     //还有一个超时的用法,队列空时,指定阻塞时间后返回,不会一直阻塞
                     //但有一个疑问,既然可以不阻塞,为啥还叫阻塞队列?
                    //System.out.println(name+" Consumer " +  concurrentLinkedQueue.poll(300, TimeUnit.MILLISECONDS));                    
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }  

         }  
     }  
 }  
}

4、PriorityBlockingQueue

基于优先级的阻塞队列(优先级的判断通过构造函数传入的Compator对象来决定,也就是说传入队列的对象必须实现Comparable接口),在实现PriorityBlockingQueue时,内部控制线程同步的锁采用的是公平锁,他也是一个无界的队列。

5、PriorityBlockingQueue 实例

Task.java

public class Task implements Comparable<Task>{

    private int id ;
    private String name;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }

    @Override
    public int compareTo(Task task) {
        return this.id > task.id ? 1 : (this.id < task.id ? -1 : 0);  
    }

    public String toString(){
        return this.id + "," + this.name;
    }

}
View Code

UsePriorityBlockingQueue.java

public class UsePriorityBlockingQueue {

    public static void main(String[] args) throws Exception{

        PriorityBlockingQueue<Task> q2 = new PriorityBlockingQueue<Task>();

        Task t1 = new Task();
        t1.setId(3);
        t1.setName("id为3");
        Task t2 = new Task();
        t2.setId(4);
        t2.setName("id为4");
        Task t3 = new Task();
        t3.setId(1);
        t3.setName("id为1");
        Task t4 = new Task();
        t4.setId(2);
        t4.setName("id为2");

        //return this.id > task.id ? 1 : 0;
        q2.add(t1); //3
        q2.add(t2); //4
        q2.add(t3);  //1
        q2.add(t4);

        // 1 3 4
        //第一次取值时候是取最小的后面不做排序
        System.out.println("容器:" + q2);  //[1,id为1, 2,id为2, 3,id为3, 4,id为4]
        //拿出一个元素后  又会取一个最小的出来 放在第一个
        System.out.println(q2.take().getId());
        System.out.println("容器:" + q2);    //[2,id为2, 4,id为4, 3,id为3]
        System.out.println(q2.take().getId());
        System.out.println("容器:" + q2);  //[3,id为3, 4,id为4]
    }
}
View Code

打印结果:

容器:[1,id为1, 2,id为2, 3,id为3, 4,id为4]
1
容器:[2,id为2, 4,id为4, 3,id为3]
2
容器:[3,id为3, 4,id为4]
View Code

6、DelayQueue

带有延迟时间的Queue,其中的元素只有当其指定的延迟时间到了,才能够从队列中获取到该元素。DelayQueue中的元素必须实现Delayed接口,DelayQueue是一个没有大小限制的队列,应用场景很多,比如对缓存超时的数据进行移除、任务超时处理、空闲连接的关闭等等。

7、DelayQueue实例

Wangmin.java

public class Wangmin implements Delayed {  

    private String name;  
    //身份证  
    private String id;  
    //截止时间  
    private long endTime;  
    //定义时间工具类
    private TimeUnit timeUnit = TimeUnit.SECONDS;

    public Wangmin(String name,String id,long endTime){  
        this.name=name;  
        this.id=id;  
        this.endTime = endTime;  
    }  

    public String getName(){  
        return this.name;  
    }  

    public String getId(){  
        return this.id;  
    }  

    /** 
     * 用来判断是否到了截止时间 
     */  
    @Override  
    public long getDelay(TimeUnit unit) { 
        //return unit.convert(endTime, TimeUnit.MILLISECONDS) - unit.convert(System.currentTimeMillis(), TimeUnit.MILLISECONDS);
        return endTime - System.currentTimeMillis();
    }  

    /** 
     * 相互批较排序用 
     */  
    @Override  
    public int compareTo(Delayed delayed) {  
        Wangmin w = (Wangmin)delayed;  
        return this.getDelay(this.timeUnit) - w.getDelay(this.timeUnit) > 0 ? 1:0;  
    }  

} 
View Code

WangBa.java

public class WangBa implements Runnable {  

    private DelayQueue<Wangmin> queue = new DelayQueue<Wangmin>();  

    public boolean yinye =true;  

    public void shangji(String name,String id,int money){  
        Wangmin man = new Wangmin(name, id, 1000 * money + System.currentTimeMillis());  
        System.out.println("网名"+man.getName()+" 身份证"+man.getId()+"交钱"+money+"块,开始上机...");  
        this.queue.add(man);  
    }  

    public void xiaji(Wangmin man){  
        System.out.println("网名"+man.getName()+" 身份证"+man.getId()+"时间到下机...");  
    }  

    @Override  
    public void run() {  
        while(yinye){  
            try {  
                Wangmin man = queue.take();  
                xiaji(man);  
            } catch (InterruptedException e) {  
                e.printStackTrace();  
            }  
        }  
    }  

    public static void main(String args[]){  
        try{  
            System.out.println("网吧开始营业");  
            WangBa siyu = new WangBa();  
            Thread shangwang = new Thread(siyu);  
            shangwang.start();  

            siyu.shangji("路人甲", "123", 1);  
            siyu.shangji("路人乙", "234", 10);  
            siyu.shangji("路人丙", "345", 5);  
        }  
        catch(Exception e){  
            e.printStackTrace();
        }  

    }  
} 
View Code

打印结果:

网吧开始营业
网名路人甲 身份证123交钱1块,开始上机...
网名路人乙 身份证234交钱10块,开始上机...
网名路人丙 身份证345交钱5块,开始上机...
网名路人甲 身份证123时间到下机...
网名路人丙 身份证345时间到下机...
网名路人乙 身份证234时间到下机...
View Code

8、LinkedBlockingDeque

  LinkedBlockingDeque是一个线程安全的双端队列实现,由链表结构组成的双向阻塞队列,即可以从队列的两端插入和移除元素。双向队列因为多了一个操作队列的入口,在多线程同时入队时,也就减少了一半的竞争。可以说他是最为复杂的一种队列,在内部实现维护了前端和后端节点,但是其没有实现读写分离,因此同一时间只能有一个线程对其讲行操作。在高并发中性能要远低于其它BlockingQueue。更要低于ConcurrentLinkedQueue,jdk早期有一个非线程安全的Deque就是ArryDeque了, java6里添加了LinkBlockingDeque来弥补多线程场景下线程安全的问题。

相比于其他阻塞队列,LinkedBlockingDeque多了addFirst、addLast、peekFirst、peekLast等方法,以first结尾的方法,表示插入、获取获移除双端队列的第一个元素。以last结尾的方法,表示插入、获取获移除双端队列的最后一个元素。

此外,LinkedBlockingDeque还是可选容量的,防止过度膨胀,默认等于Integer.MAX_VALUE。

主要方法:

  akeFirst()和takeLast():分别返回类表中第一个和最后一个元素,返回的元素会从类表中移除。如果列表为空,调用的方法的线程将会被阻塞直达列表中有可用元素。

  getFirst()和getLast():分别返回类表中第一个和最后一个元素,返回的元素不会从列表中移除。如果列表为空,则抛出NoSuckElementException异常。

  peek()、peekFirst()和peekLast():分别返回列表中第一个元素和最后一个元素,返回元素不会被移除。如果列表为空返回null。

  poll()、pollFirst()和pollLast():分别返回类表中第一个和最后一个元素,返回的元素会从列表中移除。如果列表为空,返回Null。

public class UseDeque {
    public static void main(String[] args) {
        LinkedBlockingDeque<String> dq = new LinkedBlockingDeque<String>(10);
        dq.addFirst("a");
        dq.addFirst("b");
        dq.addFirst("c");
        dq.addFirst("d");
        dq.addFirst("e");
        dq.addLast("f");
        dq.addLast("g");
        dq.addLast("h");
        dq.addLast("i");
        dq.addLast("j");
        //dq.offerFirst("k");
        System.out.println("查看头元素:" + dq.peekFirst());
        System.out.println("获取尾元素:" + dq.pollLast());
        Object [] objs = dq.toArray();
        for (int i = 0; i < objs.length; i++) {
            System.out.print(objs[i] + " -- ");
        }
    }
}

打印结果:

查看头元素:e
获取尾元素:j
e -- d -- c -- b -- a -- f -- g -- h -- i -- 
View Code

9、LinkedBlockingDeque方法列表

// 创建一个容量为 Integer.MAX_VALUE 的 LinkedBlockingDeque。
LinkedBlockingDeque()
// 创建一个容量为 Integer.MAX_VALUE 的 LinkedBlockingDeque,最初包含给定 collection 的元素,以该 collection 迭代器的遍历顺序添加。
LinkedBlockingDeque(Collection<? extends E> c)
// 创建一个具有给定(固定)容量的 LinkedBlockingDeque。
LinkedBlockingDeque(int capacity)

// 在不违反容量限制的情况下,将指定的元素插入此双端队列的末尾。
boolean add(E e)
// 如果立即可行且不违反容量限制,则将指定的元素插入此双端队列的开头;如果当前没有空间可用,则抛出 IllegalStateException。
void addFirst(E e)
// 如果立即可行且不违反容量限制,则将指定的元素插入此双端队列的末尾;如果当前没有空间可用,则抛出 IllegalStateException。
void addLast(E e)
// 以原子方式 (atomically) 从此双端队列移除所有元素。
void clear()
// 如果此双端队列包含指定的元素,则返回 true。
boolean contains(Object o)
// 返回在此双端队列的元素上以逆向连续顺序进行迭代的迭代器。
Iterator<E> descendingIterator()
// 移除此队列中所有可用的元素,并将它们添加到给定 collection 中。
int drainTo(Collection<? super E> c)
// 最多从此队列中移除给定数量的可用元素,并将这些元素添加到给定 collection 中。
int drainTo(Collection<? super E> c, int maxElements)
// 获取但不移除此双端队列表示的队列的头部。
E element()
// 获取,但不移除此双端队列的第一个元素。
E getFirst()
// 获取,但不移除此双端队列的最后一个元素。
E getLast()
// 返回在此双端队列元素上以恰当顺序进行迭代的迭代器。
Iterator<E> iterator()
// 如果立即可行且不违反容量限制,则将指定的元素插入此双端队列表示的队列中(即此双端队列的尾部),并在成功时返回 true;如果当前没有空间可用,则返回 false。
boolean offer(E e)
// 将指定的元素插入此双端队列表示的队列中(即此双端队列的尾部),必要时将在指定的等待时间内一直等待可用空间。
boolean offer(E e, long timeout, TimeUnit unit)
// 如果立即可行且不违反容量限制,则将指定的元素插入此双端队列的开头,并在成功时返回 true;如果当前没有空间可用,则返回 false。
boolean offerFirst(E e)
// 将指定的元素插入此双端队列的开头,必要时将在指定的等待时间内等待可用空间。
boolean offerFirst(E e, long timeout, TimeUnit unit)
// 如果立即可行且不违反容量限制,则将指定的元素插入此双端队列的末尾,并在成功时返回 true;如果当前没有空间可用,则返回 false。
boolean offerLast(E e)
// 将指定的元素插入此双端队列的末尾,必要时将在指定的等待时间内等待可用空间。
boolean offerLast(E e, long timeout, TimeUnit unit)
// 获取但不移除此双端队列表示的队列的头部(即此双端队列的第一个元素);如果此双端队列为空,则返回 null。
E peek()
// 获取,但不移除此双端队列的第一个元素;如果此双端队列为空,则返回 null。
E peekFirst()
// 获取,但不移除此双端队列的最后一个元素;如果此双端队列为空,则返回 null。
E peekLast()
// 获取并移除此双端队列表示的队列的头部(即此双端队列的第一个元素);如果此双端队列为空,则返回 null。
E poll()
// 获取并移除此双端队列表示的队列的头部(即此双端队列的第一个元素),如有必要将在指定的等待时间内等待可用元素。
E poll(long timeout, TimeUnit unit)
// 获取并移除此双端队列的第一个元素;如果此双端队列为空,则返回 null。
E pollFirst()
// 获取并移除此双端队列的第一个元素,必要时将在指定的等待时间等待可用元素。
E pollFirst(long timeout, TimeUnit unit)
// 获取并移除此双端队列的最后一个元素;如果此双端队列为空,则返回 null。
E pollLast()
// 获取并移除此双端队列的最后一个元素,必要时将在指定的等待时间内等待可用元素。
E pollLast(long timeout, TimeUnit unit)
// 从此双端队列所表示的堆栈中弹出一个元素。
E pop()
// 将元素推入此双端队列表示的栈。
void push(E e)
// 将指定的元素插入此双端队列表示的队列中(即此双端队列的尾部),必要时将一直等待可用空间。
void put(E e)
// 将指定的元素插入此双端队列的开头,必要时将一直等待可用空间。
void putFirst(E e)
// 将指定的元素插入此双端队列的末尾,必要时将一直等待可用空间。
void putLast(E e)
// 返回理想情况下(没有内存和资源约束)此双端队列可不受阻塞地接受的额外元素数。
int remainingCapacity()
// 获取并移除此双端队列表示的队列的头部。
E remove()
// 从此双端队列移除第一次出现的指定元素。
boolean remove(Object o)
// 获取并移除此双端队列第一个元素。
E removeFirst()
// 从此双端队列移除第一次出现的指定元素。
boolean removeFirstOccurrence(Object o)
// 获取并移除此双端队列的最后一个元素。
E removeLast()
// 从此双端队列移除最后一次出现的指定元素。
boolean removeLastOccurrence(Object o)
// 返回此双端队列中的元素数。
int size()
// 获取并移除此双端队列表示的队列的头部(即此双端队列的第一个元素),必要时将一直等待可用元素。
E take()
// 获取并移除此双端队列的第一个元素,必要时将一直等待可用元素。
E takeFirst()
// 获取并移除此双端队列的最后一个元素,必要时将一直等待可用元素。
E takeLast()
// 返回以恰当顺序(从第一个元素到最后一个元素)包含此双端队列所有元素的数组。
Object[] toArray()
// 返回以恰当顺序包含此双端队列所有元素的数组;返回数组的运行时类型是指定数组的运行时类型。
<T> T[] toArray(T[] a)
// 返回此 collection 的字符串表示形式。
String toString()
View Code

10、LinkedBlockingQeque和LinkedBlockingDeque源码解读

1)LinkedBlockingQeque

先看它的结构基本字段:

/**
 * 基于链表。
 * FIFO
 * 单向
 *最大容量是Integer.MAX_VALUE.
 */
public class LinkedBlockingQueueAnalysis<E> extends AbstractQueue<E>
        implements BlockingQueue<E>, java.io.Serializable {
    /*
     * 两个方向。
     * putLock
     * takeLock
     * 有些操作会需要同时获取两把锁。
     * 例如remove操作,也需要获取两把锁
     */

    //主要的node节点
    static class Node<E> {
        E item;
        Node<E> next;
        Node(E x) { item = x; }
    }

    //容量,一开始就固定了的。
    private final int capacity;

    //用AtomicInteger 来记录数量。
    private final AtomicInteger count = new AtomicInteger();

    //head节点 head.item == null
    transient Node<E> head;

    //last节点,last.next == null
    private transient Node<E> last;

    //take锁
    private final ReentrantLock takeLock = new ReentrantLock();

    //等待take的节点序列。
    private final Condition notEmpty = takeLock.newCondition();

    //put的lock。
    private final ReentrantLock putLock = new ReentrantLock();

   //等待puts的队列。
    private final Condition notFull = putLock.newCondition();
    ...
}
View Code

和LinkedBlockingDeque的区别之一就是,LinkedBlockingQueue采用了两把锁来对队列进行操作,也就是队尾添加的时候, 

队头仍然可以删除等操作。接下来看典型的操作。

put操作

 public void put(E e) throws InterruptedException {
        if (e == null) throw new NullPointerException();   //e不能为null
        int c = -1;
        Node<E> node = new Node<E>(e);
        final ReentrantLock putLock = this.putLock;     //获取put锁
        final AtomicInteger count = this.count;          //获取count
        putLock.lockInterruptibly();
        try {
            while (count.get() == capacity) {        //如果满了,那么就需要使用notFull阻塞
                notFull.await();
            }
            enqueue(node);
            c = count.getAndIncrement();
            if (c + 1 < capacity)                    //如果此时又有空间了,那么notFull唤醒
                notFull.signal();
        } finally {
            putLock.unlock();             //释放锁
        }
        if (c == 0)            //当c为0时候,也要根take锁说一下,并发下
            signalNotEmpty();        //调用notEmpty        
    }
View Code

主要的思想还是比较容易理解的,现在看看enqueue 方法:

private void enqueue(Node<E> node) {        //入对操作。
        last = last.next = node;      //队尾进
}

再看看signalNotEmpty方法:

private void signalNotEmpty() {
        final ReentrantLock takeLock = this.takeLock;
        takeLock.lock();        //加锁
        try {
            notEmpty.signal();    //用于signal,notEmpty
        } finally {
            takeLock.unlock();
        }
}

take操作

take操作,就是从队列里面弹出一个元素,下面看它的详细代码:

public E take() throws InterruptedException {
        E x;
        int c = -1;            //设定一个记录变量
        final AtomicInteger count = this.count;     //获得count
        final ReentrantLock takeLock = this.takeLock;
        takeLock.lockInterruptibly();        //加锁
        try {
            while (count.get() == 0) {       //如果没有元素,那么就阻塞性等待
                notEmpty.await();
            }
            x = dequeue();            //一定可以拿到。
            c = count.getAndDecrement();
            if (c > 1)
                notEmpty.signal();        //报告还有元素,唤醒队列
        } finally {
            takeLock.unlock();
        }
        if (c == capacity)
            signalNotFull();           //解锁
        return x;
}

接下来看dequeue方法:

private E dequeue() {
        Node<E> h = head;
        Node<E> first = h.next;
        h.next = h;        // help GC 指向自己,帮助gc回收
        head = first;
        E x = first.item;       //从队头出。
        first.item = null;      //将head.item设为null。
        return x;
}

对于LinkedBlockingQueue来说,有两个ReentrantLock分别控制队头和队尾,这样就可以使得添加操作分开来做,一般的操作是获取一把锁就可以,但有些操作例如remove操作,则需要同时获取两把锁:

public boolean remove(Object o) {
        if (o == null) return false;
        fullyLock();     //获取锁
        try {
            for (Node<E> trail = head, p = trail.next;
                 p != null;
                 trail = p, p = p.next) {     //依次循环遍历
                if (o.equals(p.item)) {       //找到了
                    unlink(p, trail);       //解除链接
                    return true;
                }
            }
            return false;        //没找到,或者解除失败
        } finally {
            fullyUnlock();
        }
}

当然,除了上述的remove方法外,在Iterator的next方法,remove方法以及LBQSpliterator分割迭代器中也是需要加全锁进行操作的。

2)LinkedBlockingDeque

LinkedBlockingDeque类有三个构造方法:

public LinkedBlockingDeque()
public LinkedBlockingDeque(int capacity)
public LinkedBlockingDeque(Collection<? extends E> c)

LinkedBlockingDeque类中的数据都被封装成了Node对象:

static final class Node<E> {
    E item;
    Node<E> prev;
    Node<E> next;
 
    Node(E x) {
        item = x;
    }
}

LinkedBlockingDeque类中的重要字段如下:

// 队列双向链表首节点
transient Node<E> first;
// 队列双向链表尾节点
transient Node<E> last;
// 双向链表元素个数
private transient int count;
// 双向链表最大容量
private final int capacity;
// 全局独占锁
final ReentrantLock lock = new ReentrantLock();
// 非空Condition对象
private final Condition notEmpty = lock.newCondition();
// 非满Condition对象
private final Condition notFull = lock.newCondition();

LinkedBlockingDeque类的底层实现和LinkedBlockingQueue类很相似,都有一个全局独占锁,和两个Condition对象,用来阻塞和唤醒线程。

LinkedBlockingDeque类对元素的操作方法比较多,我们下面以putFirst、putLast、pollFirst、pollLast方法来对元素的入队、出队操作进行分析。

入队

putFirst(E e)方法是将指定的元素插入双端队列的开头,源码如下:

public void putFirst(E e) throws InterruptedException {
    // 若插入元素为null,则直接抛出NullPointerException异常
    if (e == null) throw new NullPointerException();
    // 将插入节点包装为Node节点
    Node<E> node = new Node<E>(e);
    // 获取全局独占锁
    final ReentrantLock lock = this.lock;
    lock.lock();
    try {
        while (!linkFirst(node))
            notFull.await();
    } finally {
        // 释放全局独占锁
        lock.unlock();
    }
}

入队操作是通过linkFirst(E e)方法来完成的,如下所示:

private boolean linkFirst(Node<E> node) {
    // assert lock.isHeldByCurrentThread();
    // 元素个数超出容量。直接返回false
    if (count >= capacity)
        return false;
    // 获取双向链表的首节点
    Node<E> f = first;
    // 将node设置为首节点
    node.next = f;
    first = node;
    // 若last为null,设置尾节点为node节点
    if (last == null)
        last = node;
    else
        // 更新原首节点的前驱节点
        f.prev = node;
    ++count;
    // 唤醒阻塞在notEmpty上的线程
    notEmpty.signal();
    return true;
}

若入队成功,则linkFirst(E e)方法返回true,否则,返回false。若该方法返回false,则当前线程会阻塞在notFull条件上。

putLast(E e)方法是将指定的元素插入到双端队列的末尾,源码如下:

public void putLast(E e) throws InterruptedException {
    // 若插入元素为null,则直接抛出NullPointerException异常
    if (e == null) throw new NullPointerException();
    // 将插入节点包装为Node节点
    Node<E> node = new Node<E>(e);
    // 获取全局独占锁
    final ReentrantLock lock = this.lock;
    lock.lock();
    try {
        while (!linkLast(node))
            notFull.await();
    } finally {
        // 释放全局独占锁
        lock.unlock();
    }
}

该方法和putFirst(E e)方法几乎一样,不同点在于,putLast(E e)方法通过调用linkLast(E e)方法来插入节点:

private boolean linkLast(Node<E> node) {
    // assert lock.isHeldByCurrentThread();
    // 元素个数超出容量。直接返回false
    if (count >= capacity)
        return false;
    // 获取双向链表的尾节点
    Node<E> l = last;
    // 将node设置为尾节点
    node.prev = l;
    last = node;
    // 若first为null,设置首节点为node节点
    if (first == null)
        first = node;
    else
        // 更新原尾节点的后继节点
        l.next = node;
    ++count;
    // 唤醒阻塞在notEmpty上的线程
    notEmpty.signal();
    return true;
}

若入队成功,则linkLast(E e)方法返回true,否则,返回false。若该方法返回false,则当前线程会阻塞在notFull条件上。

出队

pollFirst()方法是获取并移除此双端队列的首节点,若不存在,则返回null,源码如下:

public E pollFirst() {
    // 获取全局独占锁
    final ReentrantLock lock = this.lock;
    lock.lock();
    try {
        return unlinkFirst();
    } finally {
        // 释放全局独占锁
        lock.unlock();
    }
}

移除首节点的操作是通过unlinkFirst()方法来完成的:

private E unlinkFirst() {
    // assert lock.isHeldByCurrentThread();
    // 获取首节点
    Node<E> f = first;
    // 首节点为null,则返回null
    if (f == null)
        return null;
    // 获取首节点的后继节点
    Node<E> n = f.next;
    // 移除first,将首节点更新为n
    E item = f.item;
    f.item = null;
    f.next = f; // help GC
    first = n;
    // 移除首节点后,为空队列
    if (n == null)
        last = null;
    else
        // 将新的首节点的前驱节点设置为null
        n.prev = null;
    --count;
    // 唤醒阻塞在notFull上的线程
    notFull.signal();
    return item;
}

 

pollLast()方法是获取并移除此双端队列的尾节点,若不存在,则返回null,源码如下:

public E pollLast() {
    // 获取全局独占锁
    final ReentrantLock lock = this.lock;
    lock.lock();
    try {
        return unlinkLast();
    } finally {
        // 释放全局独占锁
        lock.unlock();
    }
}

移除尾节点的操作是通过unlinkLast()方法来完成的:

private E unlinkLast() {
    // assert lock.isHeldByCurrentThread();
    // 获取尾节点
    Node<E> l = last;
    // 尾节点为null,则返回null
    if (l == null)
        return null;
    // 获取尾节点的前驱节点
    Node<E> p = l.prev;
    // 移除尾节点,将尾节点更新为p
    E item = l.item;
    l.item = null;
    l.prev = l; // help GC
    last = p;
    // 移除尾节点后,为空队列
    if (p == null)
        first = null;
    else
        // 将新的尾节点的后继节点设置为null
        p.next = null;
    --count;
    // 唤醒阻塞在notFull上的线程
    notFull.signal();
    return item;
}

其实LinkedBlockingDeque类的入队、出队操作都是通过linkFirst、linkLast、unlinkFirst、unlinkLast这几个方法来实现的,源码读起来也比较简单。

二、ConcurrentLinkedQueue 非阻塞算法

1、非阻塞队列

基于链接节点的、无界的、线程安全。此队列按照 FIFO(先进先出)原则对元素进行排序。队列的头部 是队列中时间最长的元素。队列的尾部 是队列中时间最短的元素。新的元素插入到队列的尾部,队列检索操作从队列头部获得元素。当许多线程共享访问一个公共 collection 时,ConcurrentLinkedQueue 是一个恰当的选择。此队列不允许 null 元素。

ConcurrentLinkedQueue是一个适用于高并发场景下的队列,通过无锁的方式,实现了高并发状态下的高性能,通常ConcurrentLinkedQueue性能好于BlockingQueue。

ConcurrentLinkedQueue重要方法:

add()和offer()都是加入元素的方法(在ConcurrentLinkedQueue中,这两个方法投有任何区别)

poll()和peek()都是取头元素节点,区别在于前者会删除元素,后者不会,相当于查看。

public class UseQueue_ConcurrentLinkedQueue {


    public static void main(String[] args) throws Exception {

        //高性能无阻塞无界队列:ConcurrentLinkedQueue

        ConcurrentLinkedQueue<String> q = new ConcurrentLinkedQueue<String>();
        q.offer("a");
        q.offer("b");
        q.offer("c");
        q.offer("d");
        q.add("e");

        System.out.println("从头部取出元素,并从队列里删除 >> "+q.poll());    //a 从头部取出元素,并从队列里删除
        System.out.println("删除后的长度 >> "+q.size());    //4
        System.out.println("取出头部元素 >> "+q.peek());    //b
        System.out.println("长度 >> "+q.size());    //4
        }
}

打印结果:

从头部取出元素,并从队列里删除 >> a
删除后的长度 >> 4
取出头部元素 >> b
长度 >> 4
View Code

2、实例

import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.TimeUnit;


public class NoBlockQueue {  
       private static ConcurrentLinkedQueue<Integer> concurrentLinkedQueue = new ConcurrentLinkedQueue<Integer>();   
          
    public static void main(String[] args) {  
        ExecutorService executorService = Executors.newFixedThreadPool(2);  

        executorService.submit(new Producer("producer1"));  
        executorService.submit(new Producer("producer2"));  
        executorService.submit(new Producer("producer3"));  
        executorService.submit(new Consumer("consumer1"));  
        executorService.submit(new Consumer("consumer2"));  
        executorService.submit(new Consumer("consumer3"));  

    }  
  
    static class Producer implements Runnable {  
        private String name;  
  
        public Producer(String name) {  
            this.name = name;  
        }  
  
        public void run() {  
            for (int i = 1; i < 10; ++i) {  
                System.out.println(name+ " start producer " + i);  
                concurrentLinkedQueue.add(i);  
                try {
                    Thread.sleep(20);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                //System.out.println(name+"end producer " + i);  
            }  
        }  
    }  
  
    static class Consumer implements Runnable {  
        private String name;  
  
        public Consumer(String name) {  
            this.name = name;  
        }  
        public void run() {  
            for (int i = 1; i < 10; ++i) {  
                try {
 
                    System.out.println(name+" Consumer " +  concurrentLinkedQueue.poll());

                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }  
//                System.out.println();  
//                System.out.println(name+" end Consumer " + i);  
            }  
        }  
    }  
} 

  在并发编程中,一般推荐使用阻塞队列,这样实现可以尽量地避免程序出现意外的错误。阻塞队列使用最经典的场景就是socket客户端数据的读取和解析,读取数据的线程不断将数据放入队列,然后解析线程不断从队列取数据解析。还有其他类似的场景,只要符合生产者-消费者模型的都可以使用阻塞队列。

使用非阻塞队列,虽然能即时返回结果(消费结果),但必须自行编码解决返回为空的情况处理(以及消费重试等问题)。

另外它们都是线程安全的,不用考虑线程同步问题。

三、多线程模拟队列

package com.bjsxt.base.conn009;
 
import java.util.LinkedList;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
 
public class MyQueue {
    
    //1 需要一个承装元素的集合 
    private LinkedList<Object> list = new LinkedList<Object>();
    
    //2 需要一个计数器
    private AtomicInteger count = new AtomicInteger(0);
    
    //3 需要制定上限和下限
    private final int minSize = 0;
    
    private final int maxSize ;
    
    //4 构造方法
    public MyQueue(int size){
        this.maxSize = size;
    }
    
    //5 初始化一个对象 用于加锁
    private final Object lock = new Object();
    
    
    //put(anObject): 把anObject加到BlockingQueue里,如果BlockQueue没有空间,则调用此方法的线程被阻断,直到BlockingQueue里面有空间再继续.
    public void put(Object obj){
        synchronized (lock) {
            while(count.get() == this.maxSize){
                try {
                    lock.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            //1 加入元素
            list.add(obj);
            //2 计数器累加
            count.incrementAndGet();
            //3 通知另外一个线程(唤醒)
            lock.notify();
            System.out.println("新加入的元素为:" + obj);
        }
    }
    
    
    //take: 取走BlockingQueue里排在首位的对象,若BlockingQueue为空,阻断进入等待状态直到BlockingQueue有新的数据被加入.
    public Object take(){
        Object ret = null;
        synchronized (lock) {
            while(count.get() == this.minSize){
                try {
                    lock.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            //1 做移除元素操作
            ret = list.removeFirst();
            //2 计数器递减
            count.decrementAndGet();
            //3 唤醒另外一个线程
            lock.notify();
        }
        return ret;
    }
    
    public int getSize(){
        return this.count.get();
    }
    
    
    public static void main(String[] args) {
        
        final MyQueue mq = new MyQueue(5);
        mq.put("a");
        mq.put("b");
        mq.put("c");
        mq.put("d");
        mq.put("e");
        
        System.out.println("当前容器的长度:" + mq.getSize());
        
        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                mq.put("f");
                mq.put("g");
            }
        },"t1");
        
        t1.start();
        
        
        
        
        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        
        Thread t2 = new Thread(new Runnable() {
            @Override
            public void run() {
                Object o1 = mq.take();
                System.out.println("移除的元素为:" + o1);
                Object o2 = mq.take();
                System.out.println("移除的元素为:" + o2);
            }
        },"t2");
        
        t2.start();
            
    }
    
}
View Code

 

 

 

文章参考:

https://blog.csdn.net/bieleyang/article/details/78027032

https://blog.csdn.net/u014535678/article/details/60583225

https://blog.csdn.net/qq_33524158/article/details/78578370

转载于:https://www.cnblogs.com/java-jun-world2099/articles/10165949.html

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值