Класс DelayQueue в Java с примером
Класс DelayQueue является членом Java Collections Framework. Он принадлежит пакету java.util.concurrent. DelayQueue реализует интерфейс BlockingQueue. DelayQueue - это специализированная очередь приоритетов, которая упорядочивает элементы в зависимости от времени задержки. Это означает, что из очереди могут быть взяты только те элементы, время которых истекло.
Заголовок DelayQueue содержит элемент, срок действия которого истек за наименьшее время. Если ни одна задержка не истекла, значит, головы нет, и опрос вернет null. DelayQueue принимает только те элементы, которые принадлежат классу типа Delayed или реализуют интерфейс java.util.concurrent.Delayed. DelayQueue внутренне блокирует элементы, пока не истечет определенная задержка. DelayQueue реализует метод getDelay (TimeUnit.NANOSECONDS) для возврата оставшегося времени задержки. Экземпляр TimeUnit, переданный методу getDelay (), представляет собой Enum, который сообщает, в какой единице времени должна быть возвращена задержка. Перечисление TimeUnit может принимать ДНИ, ЧАСЫ, МИНУТЫ, СЕКУНДЫ, МИЛЛИСЕКУНД, МИКРОСЕКУНД, НАНОСЕКУНД. Эта очередь не допускает пустых элементов. Этот класс и его итератор реализуют все дополнительные методы интерфейсов Collection и Iterator. Iterator, предоставленный в методе iterator (), не гарантирует обход элементов DelayQueue в каком-либо конкретном порядке.
// Declaration of Delayed interface
public interface Delayed extends Comparable<Delayed>
{
/**
* Returns the remaining delay associated with this object, in the
* given time unit.
*
* @param unit the time unit
*
* @return the remaining delay; zero or negative values indicate
* that the delay has already elapsed
*/
long getDelay(TimeUnit unit);
}
Иерархия DelayQueue
Он реализует интерфейсы Iterable <E> , Collection <E> , BlockingQueue <E>, Queue <E>.
Объявление класса:
public class DelayQueue<E extends Delayed> extends AbstractQueue<E> implements BlockingQueue<E>
Здесь E - это тип элемента, поддерживаемый этой коллекцией.
Конструкторы DelayQueue
Чтобы создать DelayQueue, нам нужно импортировать его из java.util.concurrent.DelayQueue .
1. DelayQueue () : этот конструктор используется для создания пустой DelayQueue.
DelayQueue<E> dq = new DelayQueue<E>();
2. DelayQueue (Collection <E> c) : этот конструктор используется для создания DelayQueue с элементами коллекции отложенных экземпляров, переданных в качестве параметра.
DelayQueue<E> dq = new DelayQueue(Collection<E> c);
Ниже приведен пример программы для иллюстрации DelayQueue на Java:
Джава
// Java Program Demonstrate DelayQueue import java.util.concurrent.*; import java.util.*; // The DelayObject for DelayQueue // It must implement Delayed and // its getDelay() and compareTo() method class DelayObject implements Delayed { private String name; private long time; // Constructor of DelayObject public DelayObject(String name, long delayTime) { this .name = name; this .time = System.currentTimeMillis() + delayTime; } // Implementing getDelay() method of Delayed @Override public long getDelay(TimeUnit unit) { long diff = time - System.currentTimeMillis(); return unit.convert(diff, TimeUnit.MILLISECONDS); } // Implementing compareTo() method of Delayed @Override public int compareTo(Delayed obj) { if ( this .time < ((DelayObject)obj).time) { return - 1 ; } if ( this .time > ((DelayObject)obj).time) { return 1 ; } return 0 ; } // Implementing toString() method of Delayed @Override public String toString() { return "
{" + "name=" + name + ", time=" + time + "}" ; } } // Driver Class public class GFG { public static void main(String[] args) throws InterruptedException { // create object of DelayQueue // using DelayQueue() constructor BlockingQueue<DelayObject> DQ = new DelayQueue<DelayObject>(); // Add numbers to end of DelayQueue DQ.add( new DelayObject( "A" , 1 )); DQ.add( new DelayObject( "B" , 2 )); DQ.add( new DelayObject( "C" , 3 )); DQ.add( new DelayObject( "D" , 4 )); // print DelayQueue System.out.println( "DelayQueue: " + DQ); // create object of DelayQueue // using DelayQueue(Collection c) // constructor BlockingQueue<DelayObject> DQ2 = new DelayQueue<DelayObject>(DQ); // print DelayQueue System.out.println( "DelayQueue: " + DQ2); } } |
DelayQueue: [ {name = A, time = 1543472836003}, {name = B, time = 1543472836004}, {name = C, time = 1543472836005}, {name = D, time = 1543472836006}] DelayQueue: [ {name = A, time = 1543472836003}, {name = B, time = 1543472836004}, {name = C, time = 1543472836005}, {name = D, time = 1543472836006}]
Ниже приведен пример программы для иллюстрации методов DelayQueue в Java:
Джава
// Java Program Demonstrate DelayQueue methods import java.util.concurrent.*; import java.util.*; // The DelayObject for DelayQueue // It must implement Delayed and // its getDelay() and compareTo() method class DelayObject implements Delayed { private String name; private long time; // Constructor of DelayObject public DelayObject(String name, long delayTime) { this .name = name; this .time = System.currentTimeMillis() + delayTime; } // Implementing getDelay() method of Delayed @Override public long getDelay(TimeUnit unit) { long diff = time - System.currentTimeMillis(); return unit.convert(diff, TimeUnit.MILLISECONDS); } // Implementing compareTo() method of Delayed @Override public int compareTo(Delayed obj) { if ( this .time < ((DelayObject)obj).time) { return - 1 ; } if ( this .time > ((DelayObject)obj).time) { return 1 ; } return 0 ; } // Implementing toString() // method of Delayed @Override public String toString() { return "
{" + "name=" + name + ", time=" + time + "}" ; } } // Driver Class public class GFG { public static void main(String[] args) throws InterruptedException { // create object of DelayQueue // using DelayQueue() constructor BlockingQueue<DelayObject> DQ = new DelayQueue<DelayObject>(); // Add numbers to end of DelayQueue // using add() method DQ.add( new DelayObject( "A" , 1 )); DQ.add( new DelayObject( "B" , 2 )); DQ.add( new DelayObject( "C" , 3 )); DQ.add( new DelayObject( "D" , 4 )); // print queue System.out.println( "DelayQueue: " + DQ); // print the head using peek() method System.out.println( "Head of DelayQueue: " + DQ.peek()); // print the size using size() method System.out.println( "Size of DelayQueue: " + DQ.size()); // remove the head using poll() method System.out.println( "Head of DelayQueue: " + DQ.poll()); // print the size using size() method System.out.println( "Size of DelayQueue: " + DQ.size()); // clear the DelayQueue using clear() method DQ.clear(); System.out.println( "Size of DelayQueue" + " after clear: " + DQ.size()); } } |
DelayQueue: [ {name = A, time = 1543472845012}, {name = B, time = 1543472845013}, {name = C, time = 1543472845014}, {name = D, time = 1543472845015}] Начальник DelayQueue: {name = A, time = 1543472845012} Размер DelayQueue: 4 Начальник DelayQueue: {name = A, time = 1543472845012} Размер DelayQueue: 3 Размер DelayQueue после очистки: 0
Основные операции
1. Добавление элементов
Метод add (E e) класса DelayQueue в Java используется для вставки данного элемента в очередь задержки и возвращает истину, если элемент был успешно вставлен.
Джава
// Java program to illustrate the adding // elements to the DelayQueue import java.util.concurrent.DelayQueue; import java.util.concurrent.Delayed; import java.util.concurrent.TimeUnit; public class AddingElementsExample { public static void main(String args[]) { // Create a DelayQueue instance DelayQueue<Delayed> queue = new DelayQueue<Delayed>(); // Create an instance of Delayed Delayed obj = new Delayed() { public long getDelay(TimeUnit unit) { return 24 ; // some value is returned } public int compareTo(Delayed o) { if (o.getDelay(TimeUnit.DAYS) > this .getDelay(TimeUnit.DAYS)) return 1 ; else if (o.getDelay(TimeUnit.DAYS) == this .getDelay(TimeUnit.DAYS)) return 0 ; return - 1 ; } }; // Use the add() method to add obj to // the empty DelayQueue instance queue.add(obj); // printing size of the queue to the console System.out.println( "Size of the queue : " + queue.size()); } } |
Размер очереди: 1
2. Удаление элементов
Метод remove () класса DelayQueue в Java используется для удаления одного экземпляра данного объекта, скажем, obj, из этого объекта DelayQueue, если он присутствует. Он возвращает истину, если данный элемент успешно удален, в противном случае возвращает ложь.
Джава
// Java Program to illustrate the removing // elements of DelayQueue class import java.util.concurrent.DelayQueue; import java.util.concurrent.Delayed; import java.util.concurrent.TimeUnit; public class RemovingElementsExample { public static void main(String args[]) { // Create a DelayQueue instance DelayQueue<Delayed> queue = new DelayQueue<Delayed>(); // Create an object of type Delayed Delayed ob = new Delayed() { public long getDelay(TimeUnit unit) { return 24 ; // some value is returned } public int compareTo(Delayed o) { if (o.getDelay(TimeUnit.DAYS) > this .getDelay(TimeUnit.DAYS)) return 1 ; else if (o.getDelay(TimeUnit.DAYS) == this .getDelay(TimeUnit.DAYS)) return 0 ; return - 1 ; } }; // Add the object to DelayQueue queue.add(ob); // Print initial size of Queue System.out.println( "Initial Size : " + queue.size()); // Remove the object ob from // this DelayQueue queue.remove(ob); // Print the final size of the DelayQueue System.out.println( "Size after removing : " + queue.size()); } } |
Начальный размер: 1 Размер после снятия: 0
3. Доступ к элементам
Метод peek () класса DelayQueue используется для извлечения заголовка DelayQueue, но не удаляет его, как в случае метода poll (), где голова удаляется из DelayQueue.
Джава
// Java Program Demonstrate accessing // elements of DelayQueue import java.util.concurrent.*; import java.util.*; // The DelayObject for DelayQueue // It must implement Delayed and // its getDelay() and compareTo() method class DelayObject implements Delayed { private String name; private long time; // Constructor of DelayObject public DelayObject(String name, long delayTime) { this .name = name; this .time = System.currentTimeMillis() + delayTime; } // Implementing getDelay() method of Delayed @Override public long getDelay(TimeUnit unit) { long diff = time - System.currentTimeMillis(); return unit.convert(diff, TimeUnit.MILLISECONDS); } // Implementing compareTo() method of Delayed @Override public int compareTo(Delayed obj) { if ( this .time < ((DelayObject)obj).time) { return - 1 ; } if ( this .time > ((DelayObject)obj).time) { return 1 ; } return 0 ; } // Implementing toString() method of Delayed @Override public String toString() { return "
{" + " " + name + ", time=" + time + "}" ; } } // Driver Class public class AccessingElementsExample { public static void main(String[] args) throws InterruptedException { // create object of DelayQueue // using DelayQueue() constructor BlockingQueue<DelayObject> DQ = new DelayQueue<DelayObject>(); // Add numbers to end of DelayQueue // using add() method DQ.add( new DelayObject( "A" , 1 )); DQ.add( new DelayObject( "B" , 2 )); // Print delayqueue System.out.println( "Original DelayQueue: " + DQ + "
" ); // removing all elements DQ.clear(); // peek() method for returning head of the // DelayQueue System.out.println( "Head of the DelayQueue: " + DQ.peek()); } } |
Исходный DelayQueue: [ {A, time = 1600770273132}, {B, time = 1600770273134}] Глава DelayQueue: null
4. Перемещение
Метод iterator () класса DelayQueue используется для возврата итератора по всем элементам в DelayQueue.
Джава
// Java Program Demonstrate iterating // over DelayQueue import java.util.concurrent.*; import java.util.*; // The DelayObject for DelayQueue // It must implement Delayed and // its getDelay() and compareTo() method class DelayObject implements Delayed { private String name; private long time; // Constructor of DelayObject public DelayObject(String name, long delayTime) { this .name = name; this .time = System.currentTimeMillis() + delayTime; } // Implementing getDelay() method of Delayed @Override public long getDelay(TimeUnit unit) { long diff = time - System.currentTimeMillis(); return unit.convert(diff, TimeUnit.MILLISECONDS); } // Implementing compareTo() method of Delayed @Override public int compareTo(Delayed obj) { if ( this .time < ((DelayObject)obj).time) { return - 1 ; } if ( this .time > ((DelayObject)obj).time) { return 1 ; } return 0 ;
|