Table of Contents
Stack
Queue
Blocking Queue
Double-ended queue
Home Java javaTutorial Java stack and queue instance analysis

Java stack and queue instance analysis

May 10, 2023 pm 04:40 PM
java

    Stack

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    23

    24

    25

    26

    27

    28

    29

    30

    31

    package com.yuzhenc.collection;

     

    import java.util.Stack;

     

    /**

     * @author: yuzhenc

     * @date: 2022-03-20 15:41:36

     * @desc: com.yuzhenc.collection

     * @version: 1.0

     */

    public class Test26 {

        public static void main(String[] args) {

            Stack<String> stack = new Stack<>();

            stack.add("A");

            stack.add("B");

            stack.add("C");

            stack.add("D");

            System.out.println(stack);//[A, B, C, D]

            //判断栈是否为空

            System.out.println(stack.empty());//false

            //查看栈顶元素,不会移除

            System.out.println(stack.peek());//D

            System.out.println(stack);//[A, B, C, D]

            //查看栈顶元素,并且移除,即出栈(先进后出)

            System.out.println(stack.pop());//D

            System.out.println(stack);//[A, B, C]

            //入栈,和add方法执行的功能一样,就是返回值不同

            System.out.println(stack.push("E"));//返回入栈的元素 E

            System.out.println(stack);//[A, B, C, E]

        }

    }

    Copy after login

    Queue

    Blocking Queue

    • ArrayBlockingQueue : Does not support simultaneous reading and writing operations, the bottom layer is based on arrays;

    • LinkedBlockingQueue: Supports simultaneous reading and writing operations, high efficiency under concurrent conditions, the bottom layer is based on linked lists ;

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    23

    24

    25

    26

    27

    28

    29

    30

    31

    32

    33

    34

    35

    36

    37

    38

    39

    40

    41

    42

    43

    44

    45

    46

    47

    48

    49

    50

    51

    52

    53

    54

    55

    package com.yuzhenc.collection;

     

    import java.util.concurrent.ArrayBlockingQueue;

    import java.util.concurrent.TimeUnit;

     

    /**

     * @author: yuzhenc

     * @date: 2022-03-20 16:00:22

     * @desc: com.yuzhenc.collection

     * @version: 1.0

     */

    public class Test27 {

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

            ArrayBlockingQueue<String> arrayBlockingQueue = new ArrayBlockingQueue<>(3);

            //添加元素

            //不可以添加null,报空指针异常

            //arrayBlockingQueue.add(null);

            //arrayBlockingQueue.offer(null);

            //arrayBlockingQueue.put(null);

     

            //正常添加元素

            System.out.println(arrayBlockingQueue.add("Lili"));//true

            System.out.println(arrayBlockingQueue.offer("Amy"));//true

            arrayBlockingQueue.put("Nana");//无返回值

     

            //队列满的情况下添加元素

            //arrayBlockingQueue.add("Sam");//报非法的状态异常

            //设置最大注阻塞时间,如果时间到了队列还是满的,就不再阻塞了

            arrayBlockingQueue.offer("Daming", 3,TimeUnit.SECONDS);

            System.out.println(arrayBlockingQueue);//[Lili, Amy, Nana]

            //真正阻塞的方法,如果队列一直是满的,就一直阻塞

            //arrayBlockingQueue.put("Lingling");//运行到这永远走不下去了,阻塞了

     

            //获取元素

            //获取队首元素不移除

            System.out.println(arrayBlockingQueue.peek());//Lili

            //出队,获取队首元素并且移除

            System.out.println(arrayBlockingQueue.poll());//Lili

            System.out.println(arrayBlockingQueue);//[Amy, Nana]

            //获取队首元素,并且移除

            System.out.println(arrayBlockingQueue.take());//Amy

            System.out.println(arrayBlockingQueue);//[Nana]

     

            //清空元素

            arrayBlockingQueue.clear();

            System.out.println(arrayBlockingQueue);//[]

     

            System.out.println(arrayBlockingQueue.peek());

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

            //设置阻塞事件,如果队列为空,返回null,时间到了以后就不阻塞了

            System.out.println(arrayBlockingQueue.poll(2,TimeUnit.SECONDS));

            //真正的阻塞,队列为空

            //System.out.println(arrayBlockingQueue.take());//执行到这里走不下去了

        }

    }

    Copy after login

    SynchronousQueue: Conveniently and efficiently transfer data between threads without causing data contention in the queue;

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    23

    24

    25

    26

    27

    28

    29

    30

    31

    32

    33

    34

    35

    36

    37

    38

    39

    40

    41

    42

    package com.yuzhenc.collection;

     

    import java.util.concurrent.SynchronousQueue;

     

    /**

     * @author: yuzhenc

     * @date: 2022-03-20 21:06:47

     * @desc: com.yuzhenc.collection

     * @version: 1.0

     */

    public class Test28 {

        public static void main(String[] args) {

            SynchronousQueue sq = new SynchronousQueue();

            //创建一个线程,取数据:

            new Thread(new Runnable() {

                @Override

                public void run() {

                    while(true){

                        try {

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

                        } catch (InterruptedException e) {

                            e.printStackTrace();

                        }

                    }

                }

            }).start();

            //搞一个线程,往里面放数据:

            new Thread(new Runnable() {

                @Override

                public void run() {

                    try {

                        sq.put("aaa");

                        sq.put("bbb");

                        sq.put("ccc");

                        sq.put("ddd");

                    } catch (InterruptedException e) {

                        e.printStackTrace();

                    }

                }

            }).start();

        }

    }

    Copy after login
    • PriorityBlockingQueue: Priority blocking queue;

    • Unbounded queue, no length limit, but when you do not specify the length, the default The initial length is 11, which can also be specified manually. Of course, as data continues to be added, the bottom layer (the bottom layer is the array Object[]) will automatically expand. The program will not end until all the memory is consumed, resulting in an OutOfMemoryError memory overflow;

    • Null elements cannot be placed, and incomparable objects are not allowed (resulting in throwing ClassCastException). The object must implement an internal comparator or an external comparator;

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    23

    24

    25

    26

    27

    28

    29

    30

    31

    32

    33

    34

    35

    36

    37

    38

    39

    40

    41

    42

    43

    44

    45

    46

    47

    48

    49

    50

    51

    52

    53

    54

    55

    56

    57

    58

    59

    60

    61

    62

    63

    64

    65

    66

    package com.yuzhenc.collection;

     

    import java.util.concurrent.PriorityBlockingQueue;

     

    /**

     * @author: yuzhenc

     * @date: 2022-03-20 21:16:56

     * @desc: com.yuzhenc.collection

     * @version: 1.0

     */

    public class Test29 {

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

            PriorityBlockingQueue<Human> priorityBlockingQueue = new PriorityBlockingQueue<>();

            priorityBlockingQueue.put(new Human("Lili",25));

            priorityBlockingQueue.put(new Human("Nana",18));

            priorityBlockingQueue.put(new Human("Amy",38));

            priorityBlockingQueue.put(new Human("Sum",9));

            //没有按优先级排列

            System.out.println(priorityBlockingQueue);//[Human{name=&#39;Sum&#39;, age=9}, Human{name=&#39;Nana&#39;, age=18}, Human{name=&#39;Amy&#39;, age=38}, Human{name=&#39;Lili&#39;, age=25}]

            //出列的时候按优先级出列

            System.out.println(priorityBlockingQueue.take());//Human{name=&#39;Sum&#39;, age=9}

            System.out.println(priorityBlockingQueue.take());//Human{name=&#39;Nana&#39;, age=18}

            System.out.println(priorityBlockingQueue.take());//Human{name=&#39;Lili&#39;, age=25}

            System.out.println(priorityBlockingQueue.take());//Human{name=&#39;Amy&#39;, age=38}

        }

    }

     

    class Human implements Comparable <Human> {

        String name;

        int age;

     

        public Human() {}

     

        public Human(String name, int age) {

            this.name = name;

            this.age = age;

        }

     

        public String getName() {

            return name;

        }

     

        public void setName(String name) {

            this.name = name;

        }

     

        public int getAge() {

            return age;

        }

     

        public void setAge(int age) {

            this.age = age;

        }

     

        @Override

        public String toString() {

            return "Human{" +

                    "name=&#39;" + name + &#39;\&#39;&#39; +

                    ", age=" + age +

                    &#39;}&#39;;

        }

     

        @Override

        public int compareTo(Human o) {

            return this.age-o.age;

        }

    Copy after login
    • DelayQueue: DelayQueue is an unbounded BlockingQueue, used to place objects that implement the Delayed interface, where The object can only be taken from the queue when it expires;

    • When the producer thread calls a method such as put to add an element, the compareTo method in the Delayed interface will be triggered. Sorting is performed, which means that the order of the elements in the queue is sorted by expiration time, not the order in which they were entered into the queue. The element at the head of the queue is the earliest to expire, and the later it expires, the later it expires;

    • The consumer thread checks the element at the head of the queue. Note that it is checking, not taking out. Then call the element's getDelay method. If the value returned by this method is less than 0 or equal to 0, the consumer thread will take out the element from the queue and process it. If the value returned by the getDelay method is greater than 0, the consumer thread will take out the element from the head of the queue after the time value returned by wait. At this time, the element should have expired;

    • cannot be The null element is placed in this queue;

    • What can DelayQueue do

      • Taobao order business: If thirty after placing the order The order will be automatically canceled if there is no payment within minutes;

      • Are you hungry? Order notification: A text message notification will be sent to the user 60 seconds after the order is placed successfully;

      • Close idle connections. In the server, there are many client connections, which need to be closed after being idle for a period of time;

      • caching. Objects in the cache need to be removed from the cache after their idle time has expired;

      • Task timeout processing. When the network protocol sliding window requests reactive interaction, handle timeout unresponsive requests, etc.;

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    23

    24

    25

    26

    27

    28

    29

    30

    31

    32

    33

    34

    35

    36

    37

    38

    39

    40

    41

    42

    43

    44

    45

    46

    47

    48

    49

    50

    51

    52

    53

    54

    55

    56

    57

    58

    59

    60

    61

    62

    63

    64

    65

    66

    67

    68

    69

    70

    71

    72

    73

    74

    75

    76

    77

    78

    79

    80

    81

    82

    83

    84

    85

    86

    87

    88

    89

    90

    91

    92

    93

    94

    95

    96

    97

    98

    99

    100

    package com.yuzhenc.collection;

     

    import java.util.concurrent.DelayQueue;

    import java.util.concurrent.Delayed;

    import java.util.concurrent.TimeUnit;

     

    /**

     * @author: yuzhenc

     * @date: 2022-03-20 21:43:32

     * @desc: com.yuzhenc.collection

     * @version: 1.0

     */

    public class Test30 {

        //创建一个队列:

        DelayQueue<User> dq = new DelayQueue<>();

        //登录游戏:

        public void login(User user){

            dq.add(user);

            System.out.println("用户:[" + user.getId() +"],[" + user.getName() + "]已经登录,预计下机时间为:" + user.getEndTime() );

        }

        //时间到,退出游戏,队列中移除:

        public void logout(){

            //打印队列中剩余的人:

            System.out.println(dq);

            try {

                User user = dq.take();

                System.out.println("用户:[" + user.getId() +"],[" + user.getName() + "]上机时间到,自动退出游戏");

            } catch (InterruptedException e) {

                e.printStackTrace();

            }

        }

        //获取在线人数:

        public int onlineSize(){

            return dq.size();

        }

        //这是main方法,程序的入口

        public static void main(String[] args) {

            //创建测试类对象:

            Test30 test = new Test30();

            //添加登录的用户:

            test.login(new User(1,"张三",System.currentTimeMillis()+5000));

            test.login(new User(2,"李四",System.currentTimeMillis()+2000));

            test.login(new User(3,"王五",System.currentTimeMillis()+10000));

            //一直监控

            while(true){

                //到期的话,就自动下线:

                test.logout();

                //队列中元素都被移除了的话,那么停止监控,停止程序即可

                if(test.onlineSize() == 0){

                    break;

                }

            }

        }

    }

    class User implements Delayed {

        private int id;//用户id

        private String name;//用户名字

        private long endTime;//结束时间

        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;

        }

        public long getEndTime() {

            return endTime;

        }

        public void setEndTime(long endTime) {

            this.endTime = endTime;

        }

        public User(int id, String name, long endTime) {

            this.id = id;

            this.name = name;

            this.endTime = endTime;

        }

        //只包装用户名字就可以

        @Override

        public String toString() {

            return "User{" +

                    "name=&#39;" + name + &#39;\&#39;&#39; +

                    &#39;}&#39;;

        }

        @Override

        public long getDelay(TimeUnit unit) {

            //计算剩余时间 剩余时间小于0 <=0  证明已经到期

            return this.getEndTime() - System.currentTimeMillis();

        }

        @Override

        public int compareTo(Delayed o) {

            //队列中数据 到期时间的比较

            User other = (User)o;

            return ((Long)(this.getEndTime())).compareTo((Long)(other.getEndTime()));

        }

    }

    Copy after login

    Java stack and queue instance analysis

    Double-ended queue

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    23

    24

    25

    26

    27

    28

    29

    30

    31

    32

    33

    34

    package com.yuzhenc.collection;

     

    import java.util.Deque;

    import java.util.LinkedList;

     

    /**

     * @author: yuzhenc

     * @date: 2022-03-20 22:03:36

     * @desc: com.yuzhenc.collection

     * @version: 1.0

     */

    public class Test31 {

        public static void main(String[] args) {

            /*

            双端队列:

            Deque<E> extends Queue

            Queue一端放 一端取的基本方法  Deque是具备的

            在此基础上 又扩展了 一些 头尾操作(添加,删除,获取)的方法

             */

            Deque<String> d = new LinkedList<>() ;

            d.offer("A");

            d.offer("B");

            d.offer("C");

            System.out.println(d);//[A, B, C]

            d.offerFirst("D");

            d.offerLast("E");

            System.out.println(d);//[D, A, B, C, E]

            System.out.println(d.poll());//D

            System.out.println(d);//[A, B, C, E]

            System.out.println(d.pollFirst());//A

            System.out.println(d.pollLast());//E

            System.out.println(d);//[B, C]

        }

    }

    Copy after login

    The above is the detailed content of Java stack and queue instance analysis. For more information, please follow other related articles on the PHP Chinese website!

    Statement of this Website
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

    Hot AI Tools

    Undresser.AI Undress

    Undresser.AI Undress

    AI-powered app for creating realistic nude photos

    AI Clothes Remover

    AI Clothes Remover

    Online AI tool for removing clothes from photos.

    Undress AI Tool

    Undress AI Tool

    Undress images for free

    Clothoff.io

    Clothoff.io

    AI clothes remover

    AI Hentai Generator

    AI Hentai Generator

    Generate AI Hentai for free.

    Hot Article

    R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
    3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
    R.E.P.O. Best Graphic Settings
    3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
    R.E.P.O. How to Fix Audio if You Can't Hear Anyone
    4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
    WWE 2K25: How To Unlock Everything In MyRise
    1 months ago By 尊渡假赌尊渡假赌尊渡假赌

    Hot Tools

    Notepad++7.3.1

    Notepad++7.3.1

    Easy-to-use and free code editor

    SublimeText3 Chinese version

    SublimeText3 Chinese version

    Chinese version, very easy to use

    Zend Studio 13.0.1

    Zend Studio 13.0.1

    Powerful PHP integrated development environment

    Dreamweaver CS6

    Dreamweaver CS6

    Visual web development tools

    SublimeText3 Mac version

    SublimeText3 Mac version

    God-level code editing software (SublimeText3)

    Perfect Number in Java Perfect Number in Java Aug 30, 2024 pm 04:28 PM

    Guide to Perfect Number in Java. Here we discuss the Definition, How to check Perfect number in Java?, examples with code implementation.

    Random Number Generator in Java Random Number Generator in Java Aug 30, 2024 pm 04:27 PM

    Guide to Random Number Generator in Java. Here we discuss Functions in Java with examples and two different Generators with ther examples.

    Weka in Java Weka in Java Aug 30, 2024 pm 04:28 PM

    Guide to Weka in Java. Here we discuss the Introduction, how to use weka java, the type of platform, and advantages with examples.

    Smith Number in Java Smith Number in Java Aug 30, 2024 pm 04:28 PM

    Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

    Java Spring Interview Questions Java Spring Interview Questions Aug 30, 2024 pm 04:29 PM

    In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

    Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

    Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

    TimeStamp to Date in Java TimeStamp to Date in Java Aug 30, 2024 pm 04:28 PM

    Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

    Create the Future: Java Programming for Absolute Beginners Create the Future: Java Programming for Absolute Beginners Oct 13, 2024 pm 01:32 PM

    Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.

    See all articles