常见五大队列使用教程

1.常用五大队列使用教程
啥都不说了,直接上代码,里面注释很详细

package com.example.springb_web.utils.Queue;


import java.text.DateFormat;
import java.time.Duration;
import java.util.Comparator;
import java.util.Date;
import java.util.PriorityQueue;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

//队列分有界/无界队列,阻塞/非阻塞队列
// 阻塞队列:含BlockingQueue 关键字,当队列满之后如果还有新元素通过put入列时, 会阻塞队列
// 非阻塞队列:不含put和take方法,队列满后在入列会直接返回错误
//普通队列中常用方法:
// 添加元素:offer--队列满插入返回false,反之true;add--对offer的封装,队列满抛异常;put--队列满则阻塞
// 删除元素:remove--删除队头元素;poll--删除并返回队头元素,队列为空返回null;take--删除并返回队头元素,队列为空阻塞
// 获取元素:上面的poll和take;peek--返回队头元素,不会删除;element--peek的封装,元素存在则取出,不存在抛出异常
// 常用搭配:offer和poll(常用,效率不错,不报错);put和take(阻塞);add和remove
public class QueueTest {
    public static void main(String[] args) throws Exception {
        //普通队列
        LinkedBlockingQueue normalQueue = new LinkedBlockingQueue();
        System.out.println(normalQueue.poll());
        //normalQueue.offer(null);
        normalQueue.offer("normal1");
        normalQueue.offer("normal2");
        while (!normalQueue.isEmpty()) {
            //先进先出
            System.out.println(normalQueue.poll());
        }

        //双端队列(Deque):双端队列是指队列的头部和尾部都可以同时入队和出队的数据结构
        LinkedBlockingDeque deque = new LinkedBlockingDeque();
        deque.offer("deque1");
        deque.offerFirst("dequeFirst1");
        deque.offerFirst("dequeFirst2");
        deque.offerLast("dequeLast");
        while (!deque.isEmpty()) {
            //先进先出
            System.out.println(deque.poll());
        }

        //优先队列(PriorityQueue):优先队列是一种特殊的队列,它并不是先进先出的,而是优先级高的元素先出队。
        //优先队列根据二叉堆实现的。二叉堆分为两种类型:一种是最大堆一种是最小堆。在最大堆中,任意一个父节点的值都大于等于它左右子节点的值。
        /*Comparator comparator = new Comparator() {
            @Override
            public int compare(Object o, Object t1) {
                return 0;
            }
        };*/
        Comparator comparator = (Object obj1, Object obj2) -> {
            return Integer.valueOf(String.valueOf(obj1)) - Integer.valueOf(String.valueOf(obj2));
        };
        PriorityQueue priorityQueue = new PriorityQueue(10, comparator);
        priorityQueue.offer("9");
        priorityQueue.offer("8");
        priorityQueue.offer("37");
        priorityQueue.offer("13");
        while (!priorityQueue.isEmpty()) {
            System.out.println(priorityQueue.poll());
        }

        //延迟队列,当入队的元素到达指定的延迟时间之后方可出队
        DelayQueue delayQueue = new DelayQueue();
        delayQueue.put(new MyDelay("delay1", (long) 3000));
        delayQueue.put(new MyDelay("delay2", (long) 1000));
        System.out.println("delay--begin" + DateFormat.getDateTimeInstance().format(new Date()));
        //这里不能用poll这种方法,因为有延迟的原因,不然会持续输出很多null
        while (!delayQueue.isEmpty()) {
            System.out.println("delay--" + DateFormat.getDateTimeInstance().format(new Date()) + " " + ((MyDelay) delayQueue.take()).getMsg());
        }
        System.out.println("delay--end" + DateFormat.getDateTimeInstance().format(new Date()));


        //其他队列:如特殊的队列 SynchronousQueue,它的特别之处在于它内部没有容器,每次进行 put() 数据后(添加数据),必须等待另一个线程拿走数据后才可以再次添加数据
        SynchronousQueue synchronousQueue = new SynchronousQueue();
        //入队
        ProducerThread producerThread = new ProducerThread(synchronousQueue);
        Thread thread = new Thread(producerThread);
        thread.start();
        //出队
        new Thread(() -> {
            try {
                //这里不能用isEmpty判断,由于没有容器,synchronousQueue一直为0
                //while (!synchronousQueue.isEmpty()){
                while (true) {
                    //Thread.sleep(1000);
                    System.out.println("take:" + synchronousQueue.take());
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();

        //自定义队列,可以使用数组、链表、list等储存队列
        MyQueue myQueue = new MyQueue(10);
        myQueue.offer("myQueue1");
        myQueue.offer("myQueue2");
        System.out.println(myQueue.peek().item);
        while (!myQueue.isEmpty()){
            System.out.println(myQueue.poll().item);
        }


    }
}
class ProducerThread implements Runnable{

    private SynchronousQueue synchronousQueue;
    private AtomicInteger count = new AtomicInteger();

    public  ProducerThread(SynchronousQueue synchronousQueue){
        this.synchronousQueue = synchronousQueue;
    }

    @Override
    public void run() {
        for (int i = 0; i < 4; i++) {
            try {
                //这里发现,先进行两次put,第二次put的时会被阻塞,此时唤醒take,在第二次take时被阻塞,此时唤醒第二次put。提供者和消费者是需要组队完成工作,缺少一个将会阻塞线程,直到配对为止
                //查看逻辑,发现put和take都调用的this.transferer.transfer()方法,没有使用aqs,使用了一系列cas保证线程安全问题
                // 公平与非公平模式:
                // 1.公平模式下底层使用的是TransferQueue,是一个先进先出的队列:TransferQueue队列有一个head和tail指针,用于指向当前正在等待匹配的线程节点
                //  ①put1线程put进一条数据后,自旋后休眠,put2同理,此时head为null,tail为put2;
                //  ②take1线程进来,此时take1和put2配对,由于是公平策略(队尾匹配队头出队),唤醒的是put1,消费put1。然后take2进来匹配put2后消费。
                // 2.非公平模式底层采用了后进先出的TransferStack栈来实现:TransferStack栈中用head指针指向栈顶
                //  ①put1线程put进一条数据后,自旋后休眠,put2同理,此时put2在栈顶,head指向put2,put1在栈底,栈方向为栈底指向栈顶;
                //  ②take1进来与put2匹配,并消费,之后把head指向put1,take2进来将匹配put1后消费。
                synchronized (this.count){
                    System.out.println("put-before:synchronousQueue" + i);
                    synchronousQueue.put("synchronousQueue" + i);
                    System.out.println("put-after:synchronousQueue" + i);
                }
                count.getAndIncrement();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    };
}

class MyDelay implements Delayed{

    private String msg;
    //延迟时间
    private long delayTime;

    //初始化,传入延时时间
    public MyDelay(String msg,Long delayMills){
        this.msg = msg;
        this.delayTime = System.currentTimeMillis() + delayMills;
    }

    //获取剩余时间,必须重写,delayTime为初始化设置的时间(相当于定时了),出列会在getDelay返回0(当前时间达到设定的时间)的时候
    @Override
    public long getDelay(TimeUnit timeUnit) {
        return timeUnit.convert(Duration.ofMillis(delayTime - System.currentTimeMillis()));
    }

    //队列元素排序依据,谁剩余的延迟时间短,谁在前面。跟谁先入队列无关
    @Override
    public int compareTo(Delayed delayed) {
        if((this.delayTime-System.currentTimeMillis()) > delayed.getDelay(TimeUnit.MILLISECONDS)){
            return 1;

        }else if((this.delayTime-System.currentTimeMillis()) < delayed.getDelay(TimeUnit.MILLISECONDS)){
            return -1;
        }
        return 0;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public long getDelayTime() {
        return delayTime;
    }

    public void setDelayTime(long delayTime) {
        this.delayTime = delayTime;
    }
}

class MyQueue{
    private Node firstNode;
    private Node lastNode;
    private int size;
    private int maxSize;

    //自定义Node链表节点
    static class Node<E> {
        E item; // 当前的值
        Node<E> next; // 下一个节点
        Node(E e) {
            this.item = e;
        }
    }

    //初始化构造函数
    public MyQueue(int maxSize){
        if(maxSize <= 0){
            throw new RuntimeException("最大队列不能为空");
        }
        this.firstNode = this.lastNode = new Node(null);
        this.size = 0;
        this.maxSize = maxSize;

    }

    public boolean isEmpty(){
        return size == 0;
    }
    public void offer(Object e){
        if(maxSize <= size){
            throw new RuntimeException("队列已满");
        }
        //如果为add方法则加上这个判断
       /* if(e == null){
            throw new RuntimeException("元素不能为空");
        }*/
        Node node = new Node(e);
        //这一步是关键,将尾节点的下一节点赋值为当前传入的值(当前节点的next为空代表它为最后一个元素),并将尾节点重新定义
        lastNode = lastNode.next = node;
        //作用等同如下
        /*lastNode.next = node;
        lastNode = lastNode.next;*/
        size ++;

    }
    public Node poll(){
        if(isEmpty()){
            throw new RuntimeException("队列为空");
        }
        size -- ;
        //设置首节点并返回原首节点
        return firstNode = firstNode.next;
    }
    //查询队头元素
    public Node peek(){
        if(isEmpty()){
            throw new RuntimeException("队列为空");
        }
        return firstNode.next;//第几个节点为null
    }
}

输出结果如下:
在这里插入图片描述
2.PriorityQueue的公平与非公平模式介绍:
(1).公平模式下底层使用的是TransferQueue,是一个先进先出的队列:TransferQueue队列有一个head和tail指针,用于指向当前正在等待匹配的线程节点
①初始化

在这里插入图片描述

②put1线程put进一条数据后,自旋后休眠,put2同理,此时head为null,tail为put2;
在这里插入图片描述

③take1线程进来,此时take1和put2配对,由于是公平策略(队尾匹配队头出队),唤醒的是put1,消费put1。然后take2进来匹配put2后消费。

(2)非公平模式底层采用了后进先出的TransferStack栈来实现:TransferStack栈中用head指针指向栈顶
①put1线程put进一条数据后,自旋后休眠,put2同理,此时put2在栈顶,head指向put2,put1在栈底,栈方向为栈底指向栈顶;
在这里插入图片描述

②take1进来与put2匹配,并消费,之后把head指向put1,take2进来将匹配put1后消费。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值