📜  Java中的 DelayQueue size() 方法及示例

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

Java中的 DelayQueue size() 方法及示例

Java中 DelayQueue 类的size()方法用于返回给定队列中存在的元素数。如果元素的数量大于 Integer.MAX_VALUE,则返回 Integer.MAX_VALUE 作为此 DelayQueue 的大小。
语法

public int size()

参数:不接受任何参数。
返回值:它返回一个整数,它是队列的长度。
下面的程序说明了Java中 DelayQueue 的 size() 方法:

Java
// Java program to illustrate the size() 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 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;
            }
        };
 
        // Insert the object to this DelayQueue
        // Size of the queue after insertion will be 1
        queue.add(obj);
 
        // print the size of this DelayQueue using
        // size() method
        System.out.println("Size : " + queue.size());
    }
}


输出:
Size : 1