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


Java DelayQueue put()用法及代碼示例


Java中的DelayQueue類的put(E ele)方法用於將給定元素插入延遲隊列容器。 Hetre,E是此DelayQueue容器維護的元素的類型。

句法

public void put(E ele)

參數:此方法僅接受一個參數ele。這是將插入延遲隊列的元素。


返回值:該方法的返回類型為void,並且不返回任何值。

異常:

  • NullPointerException :如果給定值為null,則拋出該異常。

以下示例程序旨在說明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()); 
  
        // Cerate 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)



相關用法


注:本文由純淨天空篩選整理自psil123大神的英文原創作品 DelayQueue put() method in Java with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。