Java DelayQueue put()方法及示例

Java DelayQueue put()方法及示例

Java中DelayQueue类的put(E ele)方法是用来将一个给定的元素插入到延迟队列容器中。 E是这个延迟队列容器所维护的元素的类型。

语法:

public void put(E ele)

参数: 该方法只接受一个参数 ele 它是将被插入延迟队列的元素。

返回值: 该方法的返回类型是void,它不返回任何值。

异常:

  • NullPointerException : 如果给定的值是空的,它就会被抛出。

以下程序说明了Java中DelayQueue的put()方法:

程序1

// 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<Delayed> queue = new DelayQueue<Delayed>();
 
        // 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());
    }
}

输出

Before calling put() : true
After calling put() : false

程序2 :NullPointerException的演示。

// 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<Delayed> queue = new DelayQueue<Delayed>();
 
        try {
            queue.put(null);
        }
        catch (Exception e) {
            System.out.println(e);
        }
    }
}

输出

java.lang.NullPointerException

参考资料 : https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/DelayQueue.html#put(E)

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程