Java中的 DelayQueue put() 方法及示例
Java中DelayQueue 类的put(E ele) 方法用于将给定元素插入到延迟队列容器中。这里,E 是这个 DelayQueue 容器维护的元素类型。
语法:
public void put(E ele)
参数:此方法只接受一个参数ele 。它将被插入延迟队列中的元素。
返回值:方法的返回类型为void,不返回任何值。
例外:
- NullPointerException :如果给定值为 null,则抛出该异常。
下面的程序说明了Java中 DelayQueue 的 put() 方法:
程序 1 :
Java
// Java program to illustrate the put()
// 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 DelayQueue instance
DelayQueue queue = new DelayQueue();
// Initially Delay Queue is empty
System.out.println("Before calling put() : "
+ queue.isEmpty());
// Create an object of type Delayed
Delayed ele = 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;
}
};
// Insert the created object to DelayQueue
// using the put() method
queue.put(ele);
// Check if DelayQueue is empty.
System.out.println("After calling put() : "
+ queue.isEmpty());
}
}
Java
// Java program to illustrate the Exception thrown
// by put() method of DelayQueue
import java.util.concurrent.DelayQueue;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;
public class GFG {
public static void main(String args[])
{
DelayQueue queue = new DelayQueue();
try {
queue.put(null);
}
catch (Exception e) {
System.out.println(e);
}
}
}
输出:
Before calling put() : true
After calling put() : false
程序 2 :NullPointerException 的演示。
Java
// Java program to illustrate the Exception thrown
// by put() method of DelayQueue
import java.util.concurrent.DelayQueue;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;
public class GFG {
public static void main(String args[])
{
DelayQueue queue = new DelayQueue();
try {
queue.put(null);
}
catch (Exception e) {
System.out.println(e);
}
}
}
输出:
java.lang.NullPointerException
参考:https: Java/util/concurrent/DelayQueue.html#put(E)