Java中的 DelayQueue add() 方法及示例
Java中DelayQueue类的add(E ele)方法用于将给定元素插入延迟队列,如果元素插入成功则返回true。这里,E 指的是这个 DelayQueue 集合所维护的元素的类型。
语法:
public boolean add(E ele)
参数:此方法只接受一个参数ele 。它指的是将被插入延迟队列的元素。
返回值:它返回一个布尔值,如果元素已成功添加,则返回 true,否则返回 false。
例外:
- NullPointerException :如果尝试在此 DelayQueue 中插入 NULL,则此方法将引发 NullPointerException。
下面的程序说明了 DelayQueue 类的 add() 方法:
程序 1 :
Java
// Java program to illustrate the add()
// method in Java
import java.util.concurrent.DelayQueue;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;
public class GFG {
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);
System.out.println("Size of the queue : " + queue.size());
}
}
Java
// Java program to illustrate the Exception
// thrown by add() method of
// DelayQueue class
import java.util.concurrent.DelayQueue;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;
public class GFG {
public static void main(String args[])
{
// Create an instance of DelayQueue
DelayQueue queue = new DelayQueue();
// Try to add NULL to the queue
try {
queue.add(null);
}
// Catch Exception
catch (Exception e) {
// Print Exception raised
System.out.println(e);
}
}
}
输出:
Size of the queue : 1
程序 2 :演示 NullPointerException 的程序。
Java
// Java program to illustrate the Exception
// thrown by add() method of
// DelayQueue class
import java.util.concurrent.DelayQueue;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;
public class GFG {
public static void main(String args[])
{
// Create an instance of DelayQueue
DelayQueue queue = new DelayQueue();
// Try to add NULL to the queue
try {
queue.add(null);
}
// Catch Exception
catch (Exception e) {
// Print Exception raised
System.out.println(e);
}
}
}
输出:
java.lang.NullPointerException