DelayQueue的offer()方法用於在延遲隊列中插入指定的元素。它的作用類似於DelayQueue的add()方法。
用法:
public boolean offer (E e)
參數:
DelayQueue僅接受屬於Delayed類型的那些元素。因此,此元素E的類型應為Delayed。
返回值:
此方法不返回任何內容。
異常:
NullPointerException :如果指定的元素為null。
下麵的程序來說明Java中的DelayQueue offer():
例:
// Java Program Demonstrate DelayQueue offer() method
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;
// Contructor 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 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));
// Print delayqueue
System.out.println("Original DelayQueue: "
+ DQ + "\n");
// Now insert elements using offer method
DQ.offer(new DelayObject("C", 10));
DQ.offer(new DelayObject("D", 11));
DQ.offer(new DelayObject("E", 15));
DQ.offer(new DelayObject("F", 17));
// print queue
System.out.println("After insertion DelayQueue: "
+ DQ);
}
}
輸出:
Original DelayQueue: [ { A, time=1545817395066}, { B, time=1545817395067}] After insertion DelayQueue: [ { A, time=1545817395066}, { B, time=1545817395067}, { C, time=1545817395076}, { D, time=1545817395077}, { E, time=1545817395081}, { F, time=1545817395083}]
相關用法
- Java DelayQueue add()用法及代碼示例
- Java DelayQueue take()用法及代碼示例
- Java DelayQueue put()用法及代碼示例
- Java DelayQueue iterator()用法及代碼示例
- Java DelayQueue peak()用法及代碼示例
- Java DelayQueue toArray()用法及代碼示例
- Java DelayQueue drainTo()用法及代碼示例
- Java DelayQueue remainingCapacity()用法及代碼示例
- Java DelayQueue poll()用法及代碼示例
- Java DelayQueue size()用法及代碼示例
- Java ConcurrentLinkedDeque offer()用法及代碼示例
- Java BlockingQueue offer()用法及代碼示例
- Java DelayQueue remove()用法及代碼示例
- Java DelayQueue clear()用法及代碼示例
- Java BlockingDeque offer()用法及代碼示例
注:本文由純淨天空篩選整理自ProgrammerAnvesh大神的英文原創作品 DelayQueue offer() method in Java with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。