當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。