當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。