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


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。