Java队列

在Java中队列是基于Queue这个接口,不同的实现类有不同的性质,不是用数组就是用链表实现。

1、先看下这个接口提供的方法都有哪些,再具体看实现。

1)boolean add(E e);如果容量不达上限,将元素插入队列,并返回true。
2)boolean offer(E e);如果容量不达上限,将元素插入队列,并返回true。当使用capacity-restricted queue时优于add方法,这个capacity-restricted queue是什么呢?后续看下。
3)E remove();返回队列头元素,并删除。为空报NoSuchElementException异常。
4)E poll();返回队列头元素,并删除。
5)E element();返回队列头元素,但是不删除。为空报NoSuchElementException异常。
6)E peek();返回队列头元素,但是不删除。

2、Queue有两个接口BlockingQueue和Deque,Deque是两端都能增删的实现,即有队列的性质又有栈的性质,搞懂Queue,Deque也差不多了。
BlockingQueue的实现类类
1)ArrayBlockingQueue基于数组实现
offer方法

image.png

offer方法简单易懂,用了ReentrantLock,说明是线程安全,容量定长,超出返回false,用putIndex变量记录每次添加的下标,超出长度重置为0。
但是这个notEmpty.signal()干啥用的?有signal就有await,在这个类上搜下


take方法
这个take是BlockingQueue的方法,这个方法也是获取头部元素,只不过队列为空会一直等待,这个就是生产者、消费者模型。
image.png

image.png

poll方法也是线程安全的,每次获取得下标用takeIndex维护,初始值为0,超出队列长度重置。

总结下BlockingQueue定义的方法吧

1、void put(E e) throws InterruptedException;将元素插入队列,如果队列满了就等待。这个应该是offer方法被占用实现了不等待的逻辑,但是干嘛取名put,来个offerWaitIfEmpty()多好。
2、boolean offer(E e, long timeout, TimeUnit unit) throws InterruptedException;将元素插入队列,如果队列满了就等待传入的时间。
3、E take() throws InterruptedException;
4、poll(long timeout, TimeUnit unit) throws InterruptedException;意义上是take的重载方法,加了等待的超时间。
5、int remainingCapacity();返回可用容量。
6、int drainTo(Collection<? super E> c);将当前队列的值全部转移到传入c中。另一个重载方法是可以限定转移的最大条数。

2)DelayQueue。

LinkedBlockingQueue这个就不讲了,链表实现,源码解读没什么难度。
DelayQueue是延时队列,添加元素的时候可以设置时间,获取时候只能获取到过期的元素。
jdk居然没有给demo,参考定时任务写个demo吧

public class DelayQueueDemo {
    public static void main(String[] args) throws InterruptedException {
        DelayQueue<DelayDemo> delayeds = new DelayQueue<>();
        System.out.println("执行开始时间:" + new Date());
        delayeds.offer(new DelayDemo(1, TimeUnit.SECONDS, "线程1"));
        delayeds.offer(new DelayDemo(2, TimeUnit.SECONDS, "线程2"));
        delayeds.offer(new DelayDemo(3, TimeUnit.SECONDS, "线程3"));
        DelayDemo take;
        while ((take = delayeds.take()) != null) {
            new Thread(take).start();
        }
    }
}

class DelayDemo implements Delayed, Runnable {

    private long time;
    private String threadName;

    public DelayDemo(long time, TimeUnit unit, String threadName) {
        this.time = triggerTime(time, unit);
        this.threadName = threadName;
    }

    @Override
    public long getDelay(TimeUnit unit) {
        return unit.convert(time - now(), NANOSECONDS);
    }

    @Override
    public int compareTo(Delayed o) {

        long diff = getDelay(NANOSECONDS) - o.getDelay(NANOSECONDS);
        return (diff < 0) ? -1 : (diff > 0) ? 1 : 0;
    }

    final long now() {
        return System.nanoTime();
    }

    @Override
    public void run() {
        System.out.println("当前线程为:" + threadName + "," + "当前时间为:" + new Date());
    }

    private long triggerTime(long delay, TimeUnit unit) {
        return triggerTime(unit.toNanos((delay < 0) ? 0 : delay));
    }

    long triggerTime(long delay) {
        return now() + delay;
    }

}
image.png

未完待续。。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。