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

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

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

DelayQueue 的drainTo(Collection c)方法从此 DelayQueue 中删除所有可用元素,并将它们添加到作为参数传递的给定集合中。这种方法比重复轮询这个DelayQueue效率更高。
也有失败的可能。如果 DelayQueue 尝试将队列排空到自身,将导致 IllegalArgumentException。此外,如果在操作正在进行时修改了指定的集合,则此操作的行为是未定义的。
句法:

public int drainTo (Collection c)

参数:此方法接受一个参数 c,该参数表示要从 DelayQueue 传输元素的集合。
返回值:该函数返回传输的元素数。
异常:此方法抛出以下异常:

  • UnsupportedOperationException – 如果集合无法添加元素。
  • ClassCastException – 如果元素的类停止将元素添加到集合的方法。
  • NullPointerException – 如果集合为空。
  • IllegalArgumentException – 如果方法的参数阻止它被添加到指定的集合中。

下面的程序说明了 DelayQueue.drainTo() 方法:
方案一:

Java
// Java Program Demonstrate DelayQueue drainTo() method
 
import java.util.concurrent.*;
import java.util.*;
 
// The DelayObject for DelayQueue
// It must implement Delayed and
// its getDelay() and compareTo() method
class DelayObject implements Delayed {
 
    private String name;
    private long time;
 
    // Constructor of DelayObject
    public DelayObject(String name, long delayTime)
    {
        this.name = name;
        this.time = System.currentTimeMillis()
                    + delayTime;
    }
 
    // Implementing getDelay() method of Delayed
    @Override
    public long getDelay(TimeUnit unit)
    {
        long diff = time - System.currentTimeMillis();
        return unit.convert(diff, TimeUnit.MILLISECONDS);
    }
 
    // Implementing compareTo() method of Delayed
    @Override
    public int compareTo(Delayed obj)
    {
        if (this.time < ((DelayObject)obj).time) {
            return -1;
        }
        if (this.time > ((DelayObject)obj).time) {
            return 1;
        }
        return 0;
    }
 
    // Implementing toString() method of Delayed
    @Override
    public String toString()
    {
        return "\n{"
            + " " + name + ", time=" + time + "}";
    }
}
 
// Driver Class
public class GFG {
    public static void main(String[] args) throws InterruptedException
    {
 
        // create object of DelayQueue
        // using DelayQueue() constructor
        BlockingQueue DQ
            = new DelayQueue();
 
        // Add numbers to end of DelayQueue
        // using add() method
        DQ.add(new DelayObject("A", 1));
        DQ.add(new DelayObject("B", 2));
        DQ.add(new DelayObject("C", 3));
        DQ.add(new DelayObject("D", 4));
 
        System.out.println("Before drainTo():");
        System.out.println("DelayQueue: " + DQ);
 
        // create a ArrayList to pass as parameter to drainTo()
        ArrayList array
            = new ArrayList();
 
        // Apply drainTo method and pass array as parameter
        int response = DQ.drainTo(array);
        // print no of element passed
        System.out.println("\nNo of element passed: "
                           + response);
 
        // printing Arraylist and deque
        // after applying drainTo() method
        System.out.println("\nAfter drainTo():");
        System.out.println("DelayQueue : \n"
                           + DQ);
        System.out.println("ArrayList : \n"
                           + array);
    }
}


Java
// Java Program Demonstrate DelayQueue drainTo() method
 
import java.util.concurrent.*;
import java.util.*;
 
// The DelayObject for DelayQueue
// It must implement Delayed and
// its getDelay() and compareTo() method
class DelayObject implements Delayed {
 
    private String name;
    private long time;
 
    // Constructor of DelayObject
    public DelayObject(String name, long delayTime)
    {
        this.name = name;
        this.time = System.currentTimeMillis()
                    + delayTime;
    }
 
    // Implementing getDelay() method of Delayed
    @Override
    public long getDelay(TimeUnit unit)
    {
        long diff = time - System.currentTimeMillis();
        return unit.convert(diff, TimeUnit.MILLISECONDS);
    }
 
    // Implementing compareTo() method of Delayed
    @Override
    public int compareTo(Delayed obj)
    {
        if (this.time < ((DelayObject)obj).time) {
            return -1;
        }
        if (this.time > ((DelayObject)obj).time) {
            return 1;
        }
        return 0;
    }
 
    // Implementing toString() method of Delayed
    @Override
    public String toString()
    {
        return "\n{"
            + " " + name + ", time=" + time + "}";
    }
}
 
// Driver Class
public class GFG {
    public static void main(String[] args) throws InterruptedException
    {
 
        // create object of DelayQueue
        // using DelayQueue() constructor
        BlockingQueue DQ
            = new DelayQueue();
 
        // Add numbers to end of DelayQueue
        // using add() method
        DQ.add(new DelayObject("A", 1));
        DQ.add(new DelayObject("B", 2));
        DQ.add(new DelayObject("C", 3));
        DQ.add(new DelayObject("D", 4));
 
        // create a collection with null
        ArrayList collection = null;
 
        // try to drain null DelayQueue to collection
        try {
            DQ.drainTo(collection);
        }
        catch (Exception e) {
            System.out.println("Exception: " + e);
        }
    }
}


Java
// Java Program Demonstrate DelayQueue drainTo() method
 
import java.util.concurrent.*;
import java.util.*;
 
// The DelayObject for DelayQueue
// It must implement Delayed and
// its getDelay() and compareTo() method
class DelayObject implements Delayed {
 
    private String name;
    private long time;
 
    // Constructor of DelayObject
    public DelayObject(String name, long delayTime)
    {
        this.name = name;
        this.time = System.currentTimeMillis()
                    + delayTime;
    }
 
    // Implementing getDelay() method of Delayed
    @Override
    public long getDelay(TimeUnit unit)
    {
        long diff = time - System.currentTimeMillis();
        return unit.convert(diff, TimeUnit.MILLISECONDS);
    }
 
    // Implementing compareTo() method of Delayed
    @Override
    public int compareTo(Delayed obj)
    {
        if (this.time < ((DelayObject)obj).time) {
            return -1;
        }
        if (this.time > ((DelayObject)obj).time) {
            return 1;
        }
        return 0;
    }
 
    // Implementing toString() method of Delayed
    @Override
    public String toString()
    {
        return "\n{"
            + " " + name + ", time=" + time + "}";
    }
}
 
// Driver Class
public class GFG {
    public static void main(String[] args) throws InterruptedException
    {
 
        // create object of DelayQueue
        // using DelayQueue() constructor
        BlockingQueue DQ
            = new DelayQueue();
 
        // Add numbers to end of DelayQueue
        // using add() method
        DQ.add(new DelayObject("A", 1));
        DQ.add(new DelayObject("B", 2));
        DQ.add(new DelayObject("C", 3));
        DQ.add(new DelayObject("D", 4));
 
        System.out.println("Before drainTo():");
        System.out.println("Number of elements in the DelayQueue: "
                           + DQ.size());
        System.out.println("DelayQueue: " + DQ);
 
        // create a ArrayList to pass as parameter to drainTo()
        ArrayList array
            = new ArrayList();
        // Initialize no of element passed to collection
        // using drainTo() method
        int noOfElement = 2;
        // Apply drainTo method and pass array as parameter
        int response = DQ.drainTo(array, noOfElement);
        // print no of element passed
        System.out.println("\nNo of element passed: "
                           + response);
 
        // printing Arraylist and deque
        // after applying drainTo() method
        System.out.println("\nAfter drainTo():");
        System.out.println("Number of elements in the DelayQueue: "
                           + DQ.size());
        System.out.println("DelayQueue : \n"
                           + DQ);
        System.out.println("ArrayList : \n"
                           + array);
    }
}


输出:
Before drainTo():
DelayQueue: [
{ A, time=1546842375114}, 
{ B, time=1546842375115}, 
{ C, time=1546842375116}, 
{ D, time=1546842375117}]

No of element passed: 4

After drainTo():
DelayQueue : 
[]
ArrayList : 
[
{ A, time=1546842375114}, 
{ B, time=1546842375115}, 
{ C, time=1546842375116}, 
{ D, time=1546842375117}]

程序 2 :显示由 drainTo() 方法抛出的异常的程序。

Java

// Java Program Demonstrate DelayQueue drainTo() method
 
import java.util.concurrent.*;
import java.util.*;
 
// The DelayObject for DelayQueue
// It must implement Delayed and
// its getDelay() and compareTo() method
class DelayObject implements Delayed {
 
    private String name;
    private long time;
 
    // Constructor of DelayObject
    public DelayObject(String name, long delayTime)
    {
        this.name = name;
        this.time = System.currentTimeMillis()
                    + delayTime;
    }
 
    // Implementing getDelay() method of Delayed
    @Override
    public long getDelay(TimeUnit unit)
    {
        long diff = time - System.currentTimeMillis();
        return unit.convert(diff, TimeUnit.MILLISECONDS);
    }
 
    // Implementing compareTo() method of Delayed
    @Override
    public int compareTo(Delayed obj)
    {
        if (this.time < ((DelayObject)obj).time) {
            return -1;
        }
        if (this.time > ((DelayObject)obj).time) {
            return 1;
        }
        return 0;
    }
 
    // Implementing toString() method of Delayed
    @Override
    public String toString()
    {
        return "\n{"
            + " " + name + ", time=" + time + "}";
    }
}
 
// Driver Class
public class GFG {
    public static void main(String[] args) throws InterruptedException
    {
 
        // create object of DelayQueue
        // using DelayQueue() constructor
        BlockingQueue DQ
            = new DelayQueue();
 
        // Add numbers to end of DelayQueue
        // using add() method
        DQ.add(new DelayObject("A", 1));
        DQ.add(new DelayObject("B", 2));
        DQ.add(new DelayObject("C", 3));
        DQ.add(new DelayObject("D", 4));
 
        // create a collection with null
        ArrayList collection = null;
 
        // try to drain null DelayQueue to collection
        try {
            DQ.drainTo(collection);
        }
        catch (Exception e) {
            System.out.println("Exception: " + e);
        }
    }
}
输出:
Exception: java.lang.NullPointerException

drainTo(Collection col, int maxElements)

drainTo(Collection col, int maxElements)方法最多从该队列中移除给定数量的可用元素并将它们添加到给定集合中。转移元素后,DelayQueue 只有那些没有转移到集合的元素。
句法:

drainTo(Collection c, int maxElements)

参数:此方法接受两个参数:-

  • c – 它表示从 DelayQueue.s 传输元素的集合。
  • maxElements – 这是整数类型,是指要传输到集合的最大元素数。

返回值:该函数返回传输的元素数。
异常:此方法抛出以下异常:

  • UnsupportedOperationException – 如果集合无法添加元素。
  • ClassCastException – 如果元素的类停止将元素添加到集合的方法。
  • NullPointerException – 如果集合为空。
  • IllegalArgumentException – 如果方法的参数阻止它被添加到指定的集合中。

下面的程序说明了 DelayQueue 类的drainTo(Collection col, int maxElements)方法:-
程序 :

Java

// Java Program Demonstrate DelayQueue drainTo() method
 
import java.util.concurrent.*;
import java.util.*;
 
// The DelayObject for DelayQueue
// It must implement Delayed and
// its getDelay() and compareTo() method
class DelayObject implements Delayed {
 
    private String name;
    private long time;
 
    // Constructor of DelayObject
    public DelayObject(String name, long delayTime)
    {
        this.name = name;
        this.time = System.currentTimeMillis()
                    + delayTime;
    }
 
    // Implementing getDelay() method of Delayed
    @Override
    public long getDelay(TimeUnit unit)
    {
        long diff = time - System.currentTimeMillis();
        return unit.convert(diff, TimeUnit.MILLISECONDS);
    }
 
    // Implementing compareTo() method of Delayed
    @Override
    public int compareTo(Delayed obj)
    {
        if (this.time < ((DelayObject)obj).time) {
            return -1;
        }
        if (this.time > ((DelayObject)obj).time) {
            return 1;
        }
        return 0;
    }
 
    // Implementing toString() method of Delayed
    @Override
    public String toString()
    {
        return "\n{"
            + " " + name + ", time=" + time + "}";
    }
}
 
// Driver Class
public class GFG {
    public static void main(String[] args) throws InterruptedException
    {
 
        // create object of DelayQueue
        // using DelayQueue() constructor
        BlockingQueue DQ
            = new DelayQueue();
 
        // Add numbers to end of DelayQueue
        // using add() method
        DQ.add(new DelayObject("A", 1));
        DQ.add(new DelayObject("B", 2));
        DQ.add(new DelayObject("C", 3));
        DQ.add(new DelayObject("D", 4));
 
        System.out.println("Before drainTo():");
        System.out.println("Number of elements in the DelayQueue: "
                           + DQ.size());
        System.out.println("DelayQueue: " + DQ);
 
        // create a ArrayList to pass as parameter to drainTo()
        ArrayList array
            = new ArrayList();
        // Initialize no of element passed to collection
        // using drainTo() method
        int noOfElement = 2;
        // Apply drainTo method and pass array as parameter
        int response = DQ.drainTo(array, noOfElement);
        // print no of element passed
        System.out.println("\nNo of element passed: "
                           + response);
 
        // printing Arraylist and deque
        // after applying drainTo() method
        System.out.println("\nAfter drainTo():");
        System.out.println("Number of elements in the DelayQueue: "
                           + DQ.size());
        System.out.println("DelayQueue : \n"
                           + DQ);
        System.out.println("ArrayList : \n"
                           + array);
    }
}
输出:
Before drainTo():
Number of elements in the DelayQueue: 4
DelayQueue: [
{ A, time=1546842382382}, 
{ B, time=1546842382383}, 
{ C, time=1546842382384}, 
{ D, time=1546842382385}]

No of element passed: 2

After drainTo():
Number of elements in the DelayQueue: 2
DelayQueue : 
[
{ C, time=1546842382384}, 
{ D, time=1546842382385}]
ArrayList : 
[
{ A, time=1546842382382}, 
{ B, time=1546842382383}]