当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Java DelayQueue Class用法及代码示例


DelayQueue类是 的成员Java 集合框架。它属于java.util.concurrent包。 DelayQueue 实现BlockingQueue接口。 DelayQueue是一个专门的优先队列根据元素的延迟时间对元素进行排序。这意味着只能从队列中取出那些时间已过的元素。
DelayQueue head包含最短时间过期的元素。如果没有延迟过期,则没有头,轮询将返回 null。 DelayQueue 仅接受属于类型类的元素延迟或那些实施java.util.concurrent.Delayed接口。 DelayQueue 在内部阻止元素,直到某个延迟到期。 DelayQueue 实现 getDelay(TimeUnit.NANOSECONDS) 方法返回剩余延迟时间。传递给 getDelay() 方法的 TimeUnit 实例是一个枚举,它告诉应以哪个时间单位返回延迟。TimeUnit 枚举可以采用天、小时、分、秒、毫秒、微秒、纳秒。该队列不允许空元素。这个类及其迭代器实现了所有可选方法集合迭代器接口。方法中提供的Iteratoriterator()不保证以任何特定顺序遍历 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的层次结构

DelayQueue Class in Java

它实现了可迭代<E>,集合<E>,BlockingQueue,Queue接口。

类别声明:

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,并将 Delayed 实例集合的元素作为参数传递。

DelayQueue<E> dq = new DelayQueue(Collection<E> c);

下面是一个示例程序,用于说明 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<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}]

下面是一个示例程序,用于说明 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<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}]

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

Basic Operations

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<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());
    }
}


输出
Size of the queue : 1

2. 删除元素

DelayQueue remove()Java 中 DelayQueue 类的方法用于从 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<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());
    }
}


输出
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<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 + "\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<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));
        // 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}

DelayQueue的方法

METHOD

DESCRIPTION

add(E e) 将指定元素插入此延迟队列。
DelayQueue clear() 以原子方式删除此延迟队列中的所有元素。
dropTo(Collection<? super E> c) 从此队列中删除所有可用元素并将它们添加到给定集合中。
dropTo(Collection<? super E> c, int maxElements) 从此队列中删除最多给定数量的可用元素并将它们添加到给定的集合中。
iterator() 返回此队列中所有元素(过期和未过期)的迭代器。
offer(E e) 将指定元素插入此延迟队列。
offer(E e, long timeout, TimeUnit unit) 将指定元素插入此延迟队列。
peek() 检索但不删除此队列的头部,如果此队列为空,则返回 null。
DelayQueue poll() 检索并删除此队列的头部,如果此队列没有过期延迟的元素,则返回 null。
poll(long timeout, TimeUnit unit) 检索并删除此队列的头部,如有必要,请等待,直到此队列上有已过期延迟的元素可用,或者指定的等待时间到期。
put(E e) 将指定元素插入此延迟队列。
remainingCapacity() 始终返回 Integer.MAX_VALUE,因为 DelayQueue 不受容量限制。
remove(Object o) 从此队列中删除指定元素的单个实例(如果存在),无论它是否已过期。
take() 检索并删除此队列的头部,如有必要,请等待,直到此队列上有过期延迟的元素可用。
toArray() 返回一个包含此队列中所有元素的数组。
toArray(T[] a) 返回一个包含此队列中所有元素的数组;返回数组的运行时类型是指定数组的运行时类型。

类 java.util.AbstractQueue 中声明的方法

METHOD

DESCRIPTION

AbstractQueue addAll() 将指定集合中的所有元素添加到此队列。
AbstractQueue element() 检索但不删除此队列的头部。
AbstractQueue remove() 检索并删除此队列的头部。

类 java.util.AbstractCollection 中声明的方法

METHOD

DESCRIPTION

AbstractCollection contains() 如果此集合包含指定元素,则返回 true。
AbstractCollection containsAll() 如果此集合包含指定集合中的所有元素,则返回 true。
AbstractCollection isEmpty() 如果此集合不包含任何元素,则返回 true。
AbstractCollection removeAll() 删除指定集合中也包含的所有该集合的元素(可选操作)。
AbstractCollection retainAll() 仅保留此集合中包含在指定集合中的元素(可选操作)。
AbstractCollection toString() 返回此集合的字符串表示形式。

接口 java.util.concurrent.BlockingQueue 中声明的方法

METHOD

DESCRIPTION

BlockingQueue contains() 如果此队列包含指定元素,则返回 true。

接口 java.util.Collection 中声明的方法

METHOD

DESCRIPTION

Collection addAll() 将指定集合中的所有元素添加到此集合中(可选操作)。
containsAll(集合<?> c) 如果此集合包含指定集合中的所有元素,则返回 true。
equals(Object o) 比较指定对象与此集合是否相等。
hashCode() 返回此集合的哈希码值。
isEmpty() 如果此集合不包含任何元素,则返回 true。
parallelStream() 返回一个可能并行的 Stream 并以此集合作为其源。
移除全部(集合<?> c) 删除指定集合中也包含的所有该集合的元素(可选操作)。
removeIf(Predicate<? super E> 过滤器) 删除此集合中满足给定谓词的所有元素。
keepAll(集合<?> c) 仅保留此集合中包含在指定集合中的元素(可选操作)。
size() 返回此集合中的元素数量。
spliterator() 在此集合中的元素上创建Spliterator
stream() 返回以此集合作为源的顺序 Stream。
toArray(IntFunction<T[]> 生成器) 返回一个包含此集合中所有元素的数组,使用提供的生成器函数分配返回的数组。

接口 java.lang.Iterable 中声明的方法

METHOD

DESCRIPTION

Iterable forEach() 对 Iterable 的每个元素执行给定的操作,直到处理完所有元素或该操作引发异常。

接口 java.util.Queue 中声明的方法

METHOD

DESCRIPTION

Queue element() 检索但不删除此队列的头部。
Queue remove() 检索并删除此队列的头部。

参考: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/concurrent/DelayQueue.html



相关用法


注:本文由纯净天空筛选整理自Rajput-Ji大神的英文原创作品 DelayQueue Class in Java with Example。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。