📜  Java中的DelayQueue remove()方法

📅  最后修改于: 2022-05-13 01:54:59.168000             🧑  作者: Mango

Java中的DelayQueue remove()方法

Java中 DelayQueue 类的remove()方法用于从该 DelayQueue 中删除给定对象的单个实例,例如obj (如果存在)。如果给定元素被成功删除,则返回 true,否则返回 false。

语法

public boolean remove(Object obj)

参数:此方法将单个对象obj作为参数,该参数将从该 DealyQueue 中删除。

返回值:它返回一个布尔值,如果元素已成功删除,则返回true ,否则返回false

下面的程序说明了Java中 DelayQueue 的 remove() 方法:

// Java Program to illustrate the remove method
// of DelayQueue class
  
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 queue = new DelayQueue();
  
        // Create an object of type Delayed
        Delayed ob = 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;
            }
        };
  
        // Add the object to DelayQueue
        queue.add(ob);
  
        // Print initial size of Queue
        System.out.println("Initial Size : "
                           + queue.size());
  
        // Remove the object ob from
        // this DelayQueue
        queue.remove(ob);
  
        // Print the final size of the DelayQueue
        System.out.println("Size after removing : "
                           + queue.size());
    }
}
输出:
Initial Size : 1
Size after removing : 0