JUC - 多线程之阻塞队列BlockingQueue(四)

一、队列

队列是一种特殊的线性表,特殊之处在于它只允许在表的前端 (front) 进行删除操作,而在表的后端 (rear) 进行插入操作。和栈一样,队列是一种操作受限制的线性表,进行插入操作的端称为队尾,,进行删除操作的端称为对头.

在队列中插入一个队列元素称为入队, 从队列中删除一个队列元素称为出队。 因为队列只允许在一端插入,在另一端删除,所以只有最早进入队列的元素才能最先从队列中删除,故队列又称为先进先出 (FIFO - first in first out) 线性表

二、阻塞队列

阻塞队列(BlockingQueue)是一个支持两个附加操作的队列。这两个附加的操作是:

在队列为空时,获取元素的线程阻塞等待队列变为非空

当队列满时,存储元素的线程阻塞等待队列可用

阻塞队列常用于生产者和消费者的场景,生产者是往队列里添加元素的线程,消费者是从队列里拿元素的线程。阻塞队列就是生产者存放元素的容器,而消费者也只从容器里拿元素

BlockingQueue接口继承关系图 

BlockingQueue接口实现类 

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.TimeUnit;

public class BlockQueueTest {
    public static void main(String[] args) {
        BlockingQueue blockingQueue = new SynchronousQueue();

        new Thread(()->{
            try {
                System.out.println(Thread.currentThread().getName() + " put 1");
                blockingQueue.put("1");

                System.out.println(Thread.currentThread().getName() + " put 2");
                blockingQueue.put("2");

                System.out.println(Thread.currentThread().getName() + " put 3");
                blockingQueue.put("3");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },"T1").start();


        new Thread(()->{
            try {
                TimeUnit.SECONDS.sleep(2);
                System.out.println(Thread.currentThread().getName()+" take " + blockingQueue.take());

                TimeUnit.SECONDS.sleep(2);
                System.out.println(Thread.currentThread().getName()+" take " + blockingQueue.take());

                TimeUnit.SECONDS.sleep(2);
                System.out.println(Thread.currentThread().getName()+" take " + blockingQueue.take());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },"T2").start();
    }
}

输出

T1 put 1
T2 take 1
T1 put 2
T2 take 2
T1 put 3
T2 take 3

(一)阻塞队列BlockingQueue 四种处理方式

方法/处理方式 抛出异常 返回特殊值 一直阻塞 超时退出
插入方法 add(E) offer(E) put(E) offer(E, long, TimeUnit)
移除方法 remove() poll() take() poll(long, TimeUnit)
检查方法 element() peek() 不可用 不可用

真正体现了阻塞的两个方法就是 put(E) / take()

  • 抛出异常
    当队列满的时候, 如果再向队列中插入元素, 会抛出默认的 IllegalStateException 异常.
    当队列为空时候, 如果再从队列中获取元素, 会抛出 NoSuchElementException 异常

  • 返回特殊值
    每次对队列执行插入操作, 会返回元素是否插入成功, 成功则返回 true.
    如果是获取操作, 则是从队列中获取一个元素, 没有这个元素的话, 返回值为 null.

  • 一直阻塞
    当队列满的时候, 如果生产者线程继续向队列中 put 元素, 队列将会一直阻塞生产者线程, 直到队列可用或者响应中断退出.
    当队列为 null 的时候, 如果消费者线程从队列中 take 元素, 队列会阻塞住消费者线程, 直到队列不为 null.

  • 超时退出
    当阻塞队列满时, 如果生产者线程继续向队列中插入元素, 队列会阻塞生产者线程一段时间, 如果超过了这个指定的时间, 生产者线程就会退出

1、抛出异常

当队列满的时候, 如果再向队列中插入元素, 会抛出默认的 IllegalStateException 异常.
当队列为空时候, 如果再从队列中获取元素, 会抛出 NoSuchElementException 异常

/**
     * 1、抛出异常
     * 当队列满的时候, 如果再向队列中插入元素, 会抛出默认的 IllegalStateException 异常.
     * 当队列为空时候, 如果再从队列中获取元素, 会抛出 NoSuchElementException 异常
     */
    public static void throwException(){
        BlockingQueue blockingQueue = new ArrayBlockingQueue(3);

        System.out.println(blockingQueue.add("a"));
        System.out.println(blockingQueue.add("b"));
        System.out.println(blockingQueue.add("c"));

        // java.lang.IllegalStateException: Queue full
        //System.out.println(blockingQueue.add("d"));

        // 获取队列首元素
        System.out.println(blockingQueue.element());

        System.out.println(blockingQueue.remove());
        System.out.println(blockingQueue.remove());
        System.out.println(blockingQueue.remove());

        // java.util.NoSuchElementException
        //System.out.println(blockingQueue.remove());
    }
true
true
true
a
a
b
c

add()方法

public abstract class AbstractQueue<E>
    extends AbstractCollection<E>
    implements Queue<E> {
    public boolean add(E e) {
        if (offer(e))
            return true;
        else
            throw new IllegalStateException("Queue full");
    }
}

remove()方法

public E remove() {
        E x = poll();
        if (x != null)
            return x;
        else
            throw new NoSuchElementException();
    }

2、返回特殊值

每次对队列执行插入操作, 会返回元素是否插入成功, 成功则返回 true.
如果是获取操作, 则是从队列中获取一个元素, 没有这个元素的话, 返回值为 null

/**
     * 2、返回特殊值
     * 每次对队列执行插入操作, 会返回元素是否插入成功, 成功则返回 true.
     * 如果是获取操作, 则是从队列中获取一个元素, 没有这个元素的话, 返回值为 null
     */
    public static void returnSpecial(){
        BlockingQueue blockingQueue = new ArrayBlockingQueue(3);

        System.out.println(blockingQueue.offer("a"));
        System.out.println(blockingQueue.offer("b"));
        System.out.println(blockingQueue.offer("c"));

        // 队列满了,返回false;不抛出异常
        System.out.println(blockingQueue.offer("d"));

        // 获取队列首元素
        System.out.println(blockingQueue.peek());

        System.out.println(blockingQueue.poll());
        System.out.println(blockingQueue.poll());
        System.out.println(blockingQueue.poll());

        // 队列为空,返回null;不抛出异常
        System.out.println(blockingQueue.poll());
    }

抛出异常 与 返回特殊值 方法的实现是一样的,只不过对失败的操作的处理不一样

通过 AbstractQueue 的源码可以发现,add(e),remove(),element() 都是分别基于 offer(),poll(),peek() 实现的

public boolean add(E arg0) {
		if (this.offer(arg0)) {
			return true;
		} else {
			throw new IllegalStateException("Queue full");
		}
	}
 
	public E remove() {
		Object arg0 = this.poll();
		if (arg0 != null) {
			return arg0;
		} else {
			throw new NoSuchElementException();
		}
	}
 
	public E element() {
		Object arg0 = this.peek();
		if (arg0 != null) {
			return arg0;
		} else {
			throw new NoSuchElementException();
		}
	}
    public boolean offer(E e) {
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            q.offer(e);
            // 如果原来队列为空,重置leader线程,通知available条件
            if (q.peek() == e) {
                leader = null;
                available.signal();
            }
            return true;
        } finally {
            lock.unlock();
        }
    }
 
    //因为DelayQueue不限制长度,因此添加元素的时候不会因为队列已满产生阻塞,因此带有超时的offer方法的超时设置是不起作用的
    public boolean offer(E e, long timeout, TimeUnit unit) {
        // 和不带timeout的offer方法一样
        return offer(e);
    }


    public E poll() {
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            E first = q.peek();
            if (first == null || first.getDelay(TimeUnit.NANOSECONDS) > 0)
                return null;
            else
                return q.poll();
        } finally {
            lock.unlock();
        }
    }

3、一直阻塞

当队列满的时候, 如果生产者线程继续向队列中 put 元素, 队列将会一直阻塞生产者线程, 直到队列可用或者响应中断退出
当队列为 null 的时候, 如果消费者线程从队列中 take 元素, 队列会阻塞住消费者线程, 直到队列不为 null

/**
     * 3、一直阻塞
     * 当队列满的时候, 如果生产者线程继续向队列中 put 元素, 队列将会一直阻塞生产者线程, 直到队列可用或者响应中断退出.
     * 当队列为 null 的时候, 如果消费者线程从队列中 take 元素, 队列会阻塞住消费者线程, 直到队列不为 null
     */
    public static void alwaysBlock() throws InterruptedException {
        BlockingQueue blockingQueue = new ArrayBlockingQueue(3);

        blockingQueue.put("a");
        blockingQueue.put("b");
        blockingQueue.put("c");

        // 程序一直等待
        blockingQueue.put("d");

        System.out.println(blockingQueue.take());
        System.out.println(blockingQueue.take());
        System.out.println(blockingQueue.take());

        // 程序一直等待
        System.out.println(blockingQueue.take());
    }

public void put(E e) throws InterruptedException {
        checkNotNull(e);
        final ReentrantLock lock = this.lock;
        lock.lockInterruptibly();
        try {
            while (count == items.length)
                notFull.await();
            enqueue(e);
        } finally {
            lock.unlock();
        }
    }

public E take() throws InterruptedException {
        final ReentrantLock lock = this.lock;
        lock.lockInterruptibly();
        try {
            while (count == 0)
                notEmpty.await();
            return dequeue();
        } finally {
            lock.unlock();
        }
    }

4、超时退出

当阻塞队列满时, 如果生产者线程继续向队列中插入元素, 队列会阻塞生产者线程一段时间, 如果超过了这个指定的时间, 生产者线程就会退出

/**
     * 4、超时退出
     * 当阻塞队列满时, 如果生产者线程继续向队列中插入元素, 队列会阻塞生产者线程一段时间
     * 如果超过了这个指定的时间, 生产者线程就会退出
     */
    public static void overTimeQuit() throws InterruptedException {
        BlockingQueue blockingQueue = new ArrayBlockingQueue(3);

        blockingQueue.offer("a");
        blockingQueue.offer("b");
        blockingQueue.offer("c");

        // 队列满了,超时2S退出
        blockingQueue.offer("d", 2,TimeUnit.SECONDS);

        System.out.println(blockingQueue.poll());
        System.out.println(blockingQueue.poll());
        System.out.println(blockingQueue.poll());

        // 队列为空,超时2S退出
        System.out.println(blockingQueue.poll(2,TimeUnit.SECONDS));
    }
public boolean offer(E e, long timeout, TimeUnit unit)
        throws InterruptedException {

        checkNotNull(e);
        long nanos = unit.toNanos(timeout);
        final ReentrantLock lock = this.lock;
        lock.lockInterruptibly();
        try {
            while (count == items.length) {
                if (nanos <= 0)
                    return false;
                nanos = notFull.awaitNanos(nanos);
            }
            enqueue(e);
            return true;
        } finally {
            lock.unlock();
        }
    }

public E poll(long timeout, TimeUnit unit) throws InterruptedException {
        long nanos = unit.toNanos(timeout);
        final ReentrantLock lock = this.lock;
        lock.lockInterruptibly();
        try {
            while (count == 0) {
                if (nanos <= 0)
                    return null;
                nanos = notEmpty.awaitNanos(nanos);
            }
            return dequeue();
        } finally {
            lock.unlock();
        }
    }

(二)BlockingQueue核心方法

public interface BlockingQueue<E> extends Queue<E> {
 
    //将给定元素设置到队列中,如果设置成功返回true, 否则抛出异常。如果是往限定了长度的队列中设置值,推荐使用offer()方法。
    boolean add(E e);
 
    //将给定的元素设置到队列中,如果设置成功返回true, 否则返回false. e的值不能为空,否则抛出空指针异常。
    boolean offer(E e);
 
    //将元素设置到队列中,如果队列中没有多余的空间,该方法会一直阻塞,直到队列中有多余的空间。
    void put(E e) throws InterruptedException;
 
    //将给定元素在给定的时间内设置到队列中,如果设置成功返回true, 否则返回false.
    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);
}

(三)Java中七大阻塞队列

ArrayBlockingQueue : 一个由数组结构组成的有界阻塞队列
LinkedBlockingQueue : 一个由链表结构组成的有界阻塞队列
PriorityBlockingQueue : 一个支持优先级排序的无界阻塞队列
DelayQueue: 一个使用优先级队列实现的无界阻塞队列
SynchronousQueue: 一个不存储元素的阻塞队列
LinkedTransferQueue: 一个由链表结构组成的无界阻塞队列
LinkedBlockingDeque: 一个由链表结构组成的双向阻塞队列

1、ArrayBlockingQueue

ArrayBlockingQueue是一个用数组实现的有界阻塞队列。此队列按照先进先出(FIFO)的原则对元素进行排序。默认情况下不保证访问者公平的访问队列,所谓公平访问队列是指阻塞的所有生产者线程或消费者线程,当队列可用时,可以按照阻塞的先后顺序访问队列,即先阻塞的生产者线程,可以先往队列里插入元素,先阻塞的消费者线程,可以先从队列里获取元素。通常情况下为了保证公平性会降低吞吐量。我们可以使用以下代码创建一个公平的阻塞队列:

ArrayBlockingQueue fairQueue = new ArrayBlockingQueue(1000,true);

而对于其访问的公平性,是通过ReentrantLock锁来实现的。

2、linkedBlockingQueue

linkedBlockingQueue是一个用链表实现的有界阻塞队列。此队列的默认和最大长度为Integer.MAX_VALUE。此队列按照先进先出的原则对元素进行排序。

3、PriorityBlockingQueue

PriorityBlockingQueue是一个支持优先级的无界队列。默认情况下元素采取自然顺序排列,也可以通过比较器comparator来指定元素的排序规则。元素按照升序排列。

4、DelayQueue

DelayQueue是一个支持延时获取元素的无界阻塞队列。队列使用PriorityQueue来实现。队列中的元素必须实现Delayed接口,在创建元素时可以指定多久才能从队列中获取当前元素。只有在延迟期满时才能从队列中提取元素。我们可以将DelayQueue运用在以下应用场景:

缓存系统的设计:可以用DelayQueue保存缓存元素的有效期,使用一个线程循环查询DelayQueue,一旦能从DelayQueue中获取元素时,表示缓存有效期到了。

定时任务调度。使用DelayQueue保存当天将会执行的任务和执行时间,一旦从DelayQueue中获取到任务就开始执行,从比如TimerQueue就是使用DelayQueue实现的。

如何实现Delayed接口

我们可以参考ScheduledThreadPoolExecutor里ScheduledFutureTask类。这个类实现了Delayed接口。首先:在对象创建的时候,使用time记录前对象什么时候可以使用,代码如下:

1

2

3

4

5

6

ScheduledFutureTask(Runnable r, V result, long ns, long period) {

      super(r, result);

      this.time = ns;

      this.period = period;

      this.sequenceNumber = sequencer.getAndIncrement();

}

然后使用getDelay可以查询当前元素还需要延时多久,代码如下:

1

2

3

public long getDelay(TimeUnit unit) {

 return unit.convert(time - now(), TimeUnit.NANOSECONDS);

    }

通过构造函数可以看出延迟时间参数ns的单位是纳秒,自己设计的时候最好使用纳秒,因为getDelay时可以指定任意单位,一旦以纳秒作为单位,而延时的时间又精确不到纳秒就麻烦了。使用时请注意当time小于当前时间时,getDelay会返回负数。

最后我们可以使用time的来指定其在队列中的顺序,例如:让延时时间最长的放在队列的末尾。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

public int compareTo(Delayed other) {

      if (other == this)

 return 0;

      if (other instanceof ScheduledFutureTask) {

 ScheduledFutureTask x = (ScheduledFutureTask)other;

 long diff = time - x.time;

 if (diff < 0)

   return -1;

 else if (diff > 0)

   return 1;

    else if (sequenceNumber < x.sequenceNumber)

   return -1;

 else

   return 1;

      }

    long d = (getDelay(TimeUnit.NANOSECONDS)-other.getDelay(TimeUnit.NANOSECONDS));

      return (d == 0) ? 0 : ((d < 0) ? -1 : 1);

    }

如何实现延时阻塞队列

延时阻塞队列的实现很简单,当消费者从队列里获取元素时,如果元素没有达到延时时间,就阻塞当前线程。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

long delay = first.getDelay(TimeUtil.NANOSECONDS);

if(delay<=0){

 return q.poll ;//阻塞队列

}else if(leader!=null){

  //leader表示一个等待从阻塞队列中取消息的线程

  available.await(); //让线程进入等待信号

}else {

//当leader为null,则将当前线程设置为leader

Thread thisThread = Thread.currentThread();

try{

leader = thisThread;

//使用awaitNanos()方法让当前线程等待接收信号或等待delay时间

available.awaitNanos(delay);

}finally{

 if(leader==thisThread){

   leader=null;

   }

 }

}

5、SynchronousQueue

SynchronousQueue是一个不存储元素的阻塞队列。每一个put操作必须等待一个take操作,否则不能继续添加元素。SynchronousQueue可以看成是一个传球手,负责把生产者线程处理的数据直接传递给消费者线程。队列本身并不存储任何元素,非常适合于传递性场景,比如在一个线程中使用的数据,传递给另外一个线程使用,SynchronousQueue的吞吐量高于

linkedBlockingQueue 和 ArrayBlockingQueue。

它支持公平访问队列。默认情况下依然是非公平性的策略机制

6、linkedTransferQueue

linkedTransferQueue是一个由链表结构组成的无界阻塞TransferQueue队列。相对于其他阻塞队列linkedTransferQueue多了tryTransfer和transfer方法。

transfer方法

如果当前有消费者正在等待接收元素(消费者使用take()方法或带时间限制的poll()方法时),transfer方法可以把生产者传入的元素立刻transfer(传输)给消费者。如果没有消费者在等待接收元素,transfer方法会将元素存放在队列的tail节点,并等到该元素被消费者消费了才返回。

tryTransfer方法

是用来试探下生产者传入的元素是否能直接传给消费者。如果没有消费者等待接收元素,则返回false。和transfer方法的区别是tryTransfer方法无论消费者是否接收,方法立即返回。而transfer方法是必须等到消费者消费了才返回。

对于带有时间限制的tryTransfer(E e, long timeout, TimeUnit unit)方法,则是试图把生产者传入的元素直接传给消费者,但是如果没有消费者消费该元素则等待指定的时间再返回,如果超时还没消费元素,则返回false,如果在超时时间内消费了元素,则返回true。

7、linkedBlockingDeque

linkedBlockingDeque是一个由链表结构组成的双向阻塞队列。所谓双向队列指的你可以从队列的两端插入和移出元素。双端队列因为多了一个操作队列的入口,在多线程同时入队时,也就减少了一半的竞争。相比其他的阻塞队列,linkedBlockingDeque多了addFirst,addLast,offerFirst,offerLast,peekFirst,peekLast等方法,以First单词结尾的方法,表示插入,获取(peek)或移除双端队列的第一个元素。以Last单词结尾的方法,表示插入,获取或移除双端队列的最后一个元素。另外插入方法add等同于addLast,移除方法remove等效于removeFirst。但是take方法却等同于takeFirst,不知道是不是Jdk的bug,使用时还是用带有First和Last后缀的方法更清楚。在初始化linkedBlockingDeque时可以初始化队列的容量,用来防止其再扩容时过渡膨胀。另外双向阻塞队列可以运用在“工作窃取”模式中

猜你喜欢

转载自blog.csdn.net/MinggeQingchun/article/details/127386484