当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Java DelayQueue add()用法及代码示例


Java中的DelayQueue类的add(E ele)方法用于将给定元素插入延迟队列,如果成功插入元素,则返回true。在此,E表示此DelayQueue集合维护的元素的类型。

句法

public boolean add(E ele)

参数:此方法仅使用一个参数ele。它是指将插入延迟队列的元素。


返回值:它返回一个布尔值,如果已成功添加元素,则返回true,否则返回flase。

异常:

  • NullPointerException :如果尝试在此DelayQueue中插入NULL,则此方法将引发NullPointerException。

以下示例程序旨在说明DelayQueue类的add()方法:

程序1

// 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<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); 
  
        System.out.println("Size of the queue : " + queue.size()); 
    } 
}
输出:
Size of the queue : 1

程序2:用于演示NullPointerException的程序。

// Java program to illustrate the Exception 
// thrown by add() method of 
// DelayQueue classs 
  
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<Delayed> queue = new DelayQueue<Delayed>(); 
  
        // 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


相关用法


注:本文由纯净天空筛选整理自psil123大神的英文原创作品 DelayQueue add() method in Java with Examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。