Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Analysis of stack and queue examples of Java

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly explains the "Java stack and queue example analysis", the content of the article is simple and clear, easy to learn and understand, the following please follow the editor's ideas slowly in depth, together to study and learn "Java stack and queue instance analysis" bar!

Stack package com.yuzhenc.collection;import java.util.Stack;/** * @ author: yuzhenc * @ date: 2022-03-20 15:41:36 * @ desc: com.yuzhenc.collection * @ version: 2022 * / public class Test26 {public static void main (String [] args) {Stack stack = new Stack (); stack.add ("A"); stack.add ("B"); stack.add ("C") Stack.add ("D"); System.out.println (stack); / / [A, B, C, D] / / determine whether the stack is empty System.out.println (stack.empty ()); / / false / / View the elements at the top of the stack without removing System.out.println (stack.peek ()); / / D System.out.println (stack) / / [A, B, C, D] / / View the top elements of the stack and remove them, that is, out-of-stack (first-in-first-out) System.out.println (stack.pop ()); / / D System.out.println (stack); / / [A, B, C] / / enter the stack, which is the same as the function performed by the add method, that is, to return different System.out.println (stack.push ("E")) / / returns the stacked element E System.out.println (stack); / / [A, B, C, E]} queue blocking queue

ArrayBlockingQueue: does not support read and write operations at the same time, the underlying array-based

LinkedBlockingQueue: supports simultaneous read and write operations, with high efficiency in concurrent cases, and the underlying layer is based on linked lists

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: 2022 * / public class Test27 {public static void main (String [] args) throws InterruptedException {ArrayBlockingQueue arrayBlockingQueue = new ArrayBlockingQueue (3) / / add element / / cannot add null, null pointer exception / / arrayBlockingQueue.add (null); / / arrayBlockingQueue.offer (null); / / arrayBlockingQueue.put (null); / / normally add element System.out.println (arrayBlockingQueue.add ("Lili")); / / true System.out.println (arrayBlockingQueue.offer ("Amy")) / / true arrayBlockingQueue.put ("Nana"); / No return value / / add an element / / arrayBlockingQueue.add ("Sam") when the queue is full; / / report an illegal exception / / set the maximum injection blocking time. If the time is up or the queue is full, the arrayBlockingQueue.offer is no longer blocked ("Daming", 3TIMENT.SECONDS); System.out.println (arrayBlockingQueue) / / [Lili, Amy, Nana] / / the real blocking method, blocking / / arrayBlockingQueue.put ("Lingling") if the queue is full all the time; / / blocking / / getting the element / / getting the first element of the team without removing the System.out.println (arrayBlockingQueue.peek ()) / / Lili / / get out of the queue, get the first element of the team and remove System.out.println (arrayBlockingQueue.poll ()); / / Lili System.out.println (arrayBlockingQueue); / / [Amy, Nana] / / get the first element of the team and remove System.out.println (arrayBlockingQueue.take ()); / / Amy System.out.println (arrayBlockingQueue) / / [Nana] / / clear elements arrayBlockingQueue.clear (); System.out.println (arrayBlockingQueue); / / [] System.out.println (arrayBlockingQueue.peek ()); System.out.println (arrayBlockingQueue.poll ()) / / set blocking event. If the queue is empty and null is returned, the time will not block System.out.println (arrayBlockingQueue.poll (2 TimeUnit. Second)); / / Real blocking, queue is empty / / System.out.println (arrayBlockingQueue.take ()); / / execution can't go any further}}

SynchronousQueue: transfer data between threads conveniently and efficiently without the problem of data contention in the queue

Package com.yuzhenc.collection;import java.util.concurrent.SynchronousQueue;/** * @ author: yuzhenc * @ date: 2022-03-20 21:06:47 * @ desc: com.yuzhenc.collection * @ version: 2022 * / public class Test28 {public static void main (String [] args) {SynchronousQueue sq = new SynchronousQueue () / / create a thread to fetch data: new Thread (new Runnable () {@ Override public void run () {while (true) {try {System.out.println (sq.take () } catch (InterruptedException e) {e.printStackTrace ();}) .start () / / create a thread and put data in it: 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 ();}}

PriorityBlockingQueue: blocking queue with priority

There is no limit to the length of the unbounded queue, but when you do not specify the length, the default initial length is 11, or you can specify it manually. Of course, with the continuous addition of data, the underlying layer (the underlying array Object []) will automatically expand until all memory is exhausted, resulting in the end of the OutOfMemoryError memory overflow program.

Objects that cannot be put into null elements are not allowed to be put into incomparable objects (causing ClassCastException to be thrown). Objects must implement internal comparators or external comparators.

Package com.yuzhenc.collection;import java.util.concurrent.PriorityBlockingQueue;/** * @ author: yuzhenc * @ date: 2022-03-20 21:16:56 * @ desc: com.yuzhenc.collection * @ version: 2022 * / public class Test29 {public static void main (String [] args) throws InterruptedException {PriorityBlockingQueue 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)); / / No System.out.println (priorityBlockingQueue) by priority / / [Human {name='Sum', age=9}, Human {name='Nana', age=18}, Human {name='Amy', age=38}, Human {name='Lili', age=25}] / / dequeue System.out.println (priorityBlockingQueue.take ()) by priority; / / Human {name='Sum', age=9} System.out.println (priorityBlockingQueue.take ()) / / Human {name='Nana', age=18} System.out.println (priorityBlockingQueue.take ()); / Human {name='Lili', age=25} System.out.println (priorityBlockingQueue.take ()); / / Human {name='Amy', age=38}} class Human implements Comparable {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='" + name +'\'+ ", age=" + age +'}'; @ Override public int compareTo (Human o) {return this.age-o.age;}

DelayQueue:DelayQueue is an unbounded BlockingQueue for placing objects that implement the Delayed interface, where objects can only be removed from the queue when they expire

When the producer thread calls a method such as put to add elements, it triggers the compareTo method in the Delayed interface to sort, that is, the order of the elements in the queue is sorted by expiration time, not the order in which they enter the queue. The elements at the head of the queue are the earliest to expire, and the later they expire.

The consumer thread looks at the elements in the queue header and notes that the check is not taken out. The getDelay method of the element is then called, and if the value returned by this method is less than 0 or equal to 0, the consumer thread fetches the element from the queue and processes it. If the value returned by the getDelay method is greater than 0, then the element is extracted from the queue header after the time value returned by the consumer thread wait, by which time the element should have expired

Null elements cannot be placed in such a queue

What can DelayQueue do?

Taobao order business: cancel the order automatically if there is no payment within 30 minutes after the order is issued.

Ele.me order notification: send SMS notification to the user 60 seconds after the order has been successfully placed

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

Cache. The object in the cache exceeds the idle time and needs to be removed from the cache

The task timed out. When the network protocol slides the window to request the response type interaction, handles the time-out unresponsive request, etc.

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: 2022 * / public class Test30 {/ / create a queue: DelayQueue dq = new DelayQueue () / / Log in to the game: public void login (User user) {dq.add (user); System.out.println ("user: [" + user.getId () + "], [" + user.getName () + "] has been logged in, and the estimated time to deactivate is:" + user.getEndTime ()) } / / time is up. Quit the game and remove from the queue: public void logout () {/ / print the rest of the queue: System.out.println (dq); try {User user = dq.take () System.out.println ("user: [" + user.getId () + "], [" + user.getName () + "] automatically quit the game when it's time to get on the computer;} catch (InterruptedException e) {e.printStackTrace ();}} / / get the number of online users: public int onlineSize () {return dq.size () } / / this is the main method. The entry of the program public static void main (String [] args) {/ / create the test class object: Test30 test = new Test30 (); / / add login users: test.login (new User (1, "Zhang San", System.currentTimeMillis () + 5000); test.login (new User (2, "Li Si", System.currentTimeMillis () + 2000)) Test.login (new User (3, "Wang Wu", System.currentTimeMillis () + 10000)); / / always monitor while (true) {/ / if it expires, it will be logged off automatically: test.logout () / / if all the elements in the queue are removed, then if (test.onlineSize () = = 0) {break;} class User implements Delayed {private int id;// user id private String name;// user name private long endTime;// end time 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;} / / you can @ Override public String toString () {return "User {" + "name='" + name +'\'+'}'by wrapping only user names. } @ Override public long getDelay (TimeUnit unit) {/ / calculate the remaining time is less than 0

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report