Java中的DelayQueue类与示例
DelayQueue类是Java集合框架的成员。它属于Java.util.concurrent包。 DelayQueue 实现了 BlockingQueue 接口。 DelayQueue 是一个专门的优先级队列,它根据元素的延迟时间对元素进行排序。这意味着只能从时间已过期的队列中取出那些元素。
DelayQueue 头包含在最短时间过期的元素。如果没有延迟过期,则没有头并且轮询将返回 null。 DelayQueue 仅接受属于延迟类型的类或实现Java.util.concurrent.Delayed接口的那些元素。 DelayQueue 在内部阻塞元素,直到某个延迟到期。 DelayQueue 实现 getDelay(TimeUnit.NANOSECONDS) 方法返回剩余延迟时间。传递给 getDelay() 方法的 TimeUnit 实例是一个 Enum,它告诉应以哪个时间单位返回延迟。 TimeUnit 枚举可以采用 DAYS、HOURS、MINUTES、SECONDS、MILLISECONDS、MICROSECONDS、NANOSECONDS。此队列不允许空元素。此类及其迭代器实现了Collection和Iterator接口的所有可选方法。方法 iterator() 中提供的 Iterator 不能保证以任何特定顺序遍历 DelayQueue 的元素。
// Declaration of Delayed interface
public interface Delayed extends Comparable
{
/**
* 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);
}
延迟队列的层次结构
它实现了 Iterable
类声明:
public class DelayQueue
这里, E是这个集合维护的元素的类型。
延迟队列的构造函数
要构造一个延迟队列,我们需要从Java.util.concurrent.DelayQueue中导入它。
1. DelayQueue() :该构造函数用于构造一个空的DelayQueue。
DelayQueue
2. DelayQueue(Collection
DelayQueue
下面是一个示例程序来说明Java中的 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 "\n{"
+ "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 DQ
= new DelayQueue();
// 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 DQ2
= new DelayQueue(DQ);
// print DelayQueue
System.out.println("DelayQueue: "
+ DQ2);
}
}
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 "\n{"
+ "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 DQ
= new DelayQueue();
// 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());
}
}
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 queue
= new DelayQueue();
// 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());
}
}
Java
// 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 queue = new DelayQueue();
// 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());
}
}
Java
// 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 "\n{"
+ " " + name + ", time=" + time + "}";
}
}
// Driver Class
public class AccessingElementsExample {
public static void main(String[] args)
throws InterruptedException
{
// create object of DelayQueue
// using DelayQueue() constructor
BlockingQueue DQ = new DelayQueue();
// 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 + "\n");
// removing all elements
DQ.clear();
// peek() method for returning head of the
// DelayQueue
System.out.println("Head of the DelayQueue: " + DQ.peek());
}
}
Java
// 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;
}
// Implementing toString() method of Delayed
@Override public String toString()
{
return "\n{"
+ " " + name + ", time=" + time + "}";
}
}
// Driver Class
public class IteratingExample {
public static void main(String[] args)
throws InterruptedException
{
// create object of DelayQueue
// using DelayQueue() constructor
BlockingQueue DQ = new DelayQueue();
// 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));
// Creating an iterator
Iterator val = DQ.iterator();
// print the value after iterating DelayQueue
System.out.println("The iterator values are: ");
while (val.hasNext()) {
System.out.println(val.next());
}
}
}
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}]
下面是一个示例程序来说明Java中的 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 "\n{"
+ "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 DQ
= new DelayQueue();
// 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}]
Head of DelayQueue:
{name=A, time=1543472845012}
Size of DelayQueue: 4
Head of DelayQueue:
{name=A, time=1543472845012}
Size of DelayQueue: 3
Size of DelayQueue after clear: 0
基本操作
1.添加元素
Java中DelayQueue类的add(E e)方法用于将给定元素插入延迟队列,如果元素插入成功则返回true。
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 queue
= new DelayQueue();
// 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());
}
}
Size of the queue : 1
2. 移除元素
Java中 DelayQueue 类的 remove() 方法用于从该 DelayQueue 中删除给定对象的单个实例,例如 obj(如果存在)。如果给定元素被成功删除,则返回 true,否则返回 false。
Java
// 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 queue = new DelayQueue();
// 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());
}
}
Initial Size : 1
Size after removing : 0
3. 访问元素
DelayQueue 的 peek() 方法用于检索 DelayQueue 的头部,但不会将其移除,如 poll() 方法中头部从 DelayQueue 中移除的情况。
Java
// 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 "\n{"
+ " " + name + ", time=" + time + "}";
}
}
// Driver Class
public class AccessingElementsExample {
public static void main(String[] args)
throws InterruptedException
{
// create object of DelayQueue
// using DelayQueue() constructor
BlockingQueue DQ = new DelayQueue();
// 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 + "\n");
// removing all elements
DQ.clear();
// peek() method for returning head of the
// DelayQueue
System.out.println("Head of the DelayQueue: " + DQ.peek());
}
}
Original DelayQueue: [
{ A, time=1600770273132},
{ B, time=1600770273134}]
Head of the DelayQueue: null
4. 遍历
DelayQueue 的 iterator() 方法用于返回对 DelayQueue 中所有元素的迭代器。
Java
// 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;
}
// Implementing toString() method of Delayed
@Override public String toString()
{
return "\n{"
+ " " + name + ", time=" + time + "}";
}
}
// Driver Class
public class IteratingExample {
public static void main(String[] args)
throws InterruptedException
{
// create object of DelayQueue
// using DelayQueue() constructor
BlockingQueue DQ = new DelayQueue();
// 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));
// Creating an iterator
Iterator val = DQ.iterator();
// print the value after iterating DelayQueue
System.out.println("The iterator values are: ");
while (val.hasNext()) {
System.out.println(val.next());
}
}
}
The iterator values are:
{ A, time=1600770415898}
{ B, time=1600770415900}
{ C, time=1600770415901}
{ D, time=1600770415902}
延迟队列的方法
METHOD | DESCRIPTION |
---|---|
add(E e) | Inserts the specified element into this delay queue. |
clear() | Atomically removes all of the elements from this delay queue. |
drainTo(Collection super E> c) | Removes all available elements from this queue and adds them to the given collection. |
drainTo(Collection super E> c, int maxElements) | Removes at most the given number of available elements from this queue and adds them to the given collection. |
iterator() | Returns an iterator over all the elements (both expired and unexpired) in this queue. |
offer(E e) | Inserts the specified element into this delay queue. |
offer(E e, long timeout, TimeUnit unit) | Inserts the specified element into this delay queue. |
peek() | Retrieves, but does not remove, the head of this queue, or returns null if this queue is empty. |
poll() | Retrieves and removes the head of this queue, or returns null if this queue has no elements with an expired delay. |
poll(long timeout, TimeUnit unit) | Retrieves and removes the head of this queue, waiting if necessary until an element with an expired delay is available on this queue, or the specified wait time expires. |
put(E e) | Inserts the specified element into this delay queue. |
remainingCapacity() | Always returns Integer.MAX_VALUE because a DelayQueue is not capacity constrained. |
remove(Object o) | Removes a single instance of the specified element from this queue, if it is present, whether or not it has expired. |
take() | Retrieves and removes the head of this queue, waiting if necessary until an element with an expired delay is available on this queue. |
toArray() | Returns an array containing all of the elements in this queue. |
toArray(T[] a) | Returns an array containing all of the elements in this queue; the runtime type of the returned array is that of the specified array. |
在类Java.util.AbstractQueue 中声明的方法
METHOD | DESCRIPTION |
---|---|
addAll(Collection extends E> c) | Adds all of the elements in the specified collection to this queue. |
element() | Retrieves, but does not remove, the head of this queue. |
remove() | Retrieves and removes the head of this queue. |
在类Java.util.AbstractCollection 中声明的方法
METHOD | DESCRIPTION |
---|---|
contains(Object o) | Returns true if this collection contains the specified element. |
containsAll(Collection> c) | Returns true if this collection contains all of the elements in the specified collection. |
isEmpty() | Returns true if this collection contains no elements. |
removeAll(Collection> c) | Removes all of this collection’s elements that are also contained in the specified collection (optional operation). |
retainAll(Collection> c) | Retains only the elements in this collection that are contained in the specified collection (optional operation). |
toString() | Returns a string representation of this collection. |
在接口Java.util.concurrent.BlockingQueue 中声明的方法
METHOD | DESCRIPTION |
---|---|
contains(Object o) | Returns true if this queue contains the specified element. |
在接口Java.util.Collection 中声明的方法
METHOD | DESCRIPTION |
---|---|
addAll(Collection extends E> c) | Adds all of the elements in the specified collection to this collection (optional operation). |
containsAll(Collection> c) | Returns true if this collection contains all of the elements in the specified collection. |
equals(Object o) | Compares the specified object with this collection for equality. |
hashCode() | Returns the hash code value for this collection. |
isEmpty() | Returns true if this collection contains no elements. |
parallelStream() | Returns a possibly parallel Stream with this collection as its source. |
removeAll(Collection> c) | Removes all of this collection’s elements that are also contained in the specified collection (optional operation). |
removeIf(Predicate super E> filter) | Removes all of the elements of this collection that satisfy the given predicate. |
retainAll(Collection> c) | Retains only the elements in this collection that are contained in the specified collection (optional operation). |
size() | Returns the number of elements in this collection. |
spliterator() | Creates a Spliterator over the elements in this collection. |
stream() | Returns a sequential Stream with this collection as its source. |
toArray(IntFunction | Returns an array containing all of the elements in this collection, using the provided generator function to allocate the returned array. |
在接口Java.lang.Iterable 中声明的方法
METHOD | DESCRIPTION |
---|---|
forEach(Consumer super T> action) | Performs the given action for each element of the Iterable until all elements have been processed or the action throws an exception. |
在接口Java .util.Queue 中声明的方法
METHOD | DESCRIPTION |
---|---|
element() | Retrieves, but does not remove, the head of this queue. |
remove() | Retrieves and removes the head of this queue. |
参考: Java : Java