Java BlockingQueue drainTo()方法及示例

Java BlockingQueue drainTo()方法及示例

BlockingQueue的 drainTo(Collection col) 方法从这个LinkedBlocking Queue中移除所有可用的元素,并将它们添加到作为参数的给定集合中。

注意BlockingQueuedrainTo() 方法是继承自Java中的 Queue 类。

drainTo(Collection<? super E> col)

BlockingQueue 接口的 **drainTo(Collection <? super E> col) **方法从这个队列中移除所有的元素,并将它们添加到给定的col集合中。这是一个比反复轮询这个队列更有效的方法。

当试图从队列中添加元素到集合c时,也有可能遇到失败,由于这种失败,当相关的异常被抛出时,元素被分配到两个集合中。如果一个队列试图向队列本身drainTo(),那么将抛出IllegalArgumentException。如果在操作过程中,指定的集合被修改,那么这个操作的行为就无法定义。所以在使用这类方法时,需要注意这类情况以克服异常。

语法

public int drainTo(Collection<? super E> col)

参数: 该方法接受一个参数col,代表从LinkedBlockingQueue转移元素的集合。

返回值 :该方法返回从队列中排入集合的元素数量。

异常: 该方法会抛出以下异常。

  • UnsupportedOperationException – 如果集合不能添加元素。
  • ClassCastException – 如果元素的类别阻止了添加元素到集合的方法。
  • NullPointerException – 如果集合是空的。
  • IllegalArgumentException – 如果方法的参数阻止它被添加到指定的集合中。

下面的程序说明了BlockingQueue类的drainTo()方法。

程序1:

// Java Program Demonstrate drainTo(Collection c)
// method of BlockingQueue.
  
import java.util.ArrayList;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.BlockingQueue;
  
public class GFG {
  
    // create a Employee Object with
    // position and salary as an attribute
    public class Employee {
  
        public String name;
        public String position;
        public String salary;
        Employee(String name, String position, String salary)
        {
            this.name = name;
            this.position = position;
            this.salary = salary;
        }
        @Override
        public String toString()
        {
            return "Employee [name=" + name + ", position="
                + position + ", salary=" + salary + "]";
        }
    }
  
    // Main Method
    public static void main(String[] args)
    {
        GFG gfg = new GFG();
        gfg.containsMethodExample();
    }
  
    public void containsMethodExample()
    {
  
        // define capacity of BlockingQueue
        int capacity = 50;
  
        // create object of BlockingQueue
        BlockingQueue<Employee> BQ
            = new LinkedBlockingQueue<Employee>(capacity);
  
        // create a ArrayList to pass as parameter to drainTo()
        ArrayList<Employee> collection = new ArrayList<Employee>();
  
        // add Employee object to queue
        Employee emp1 = new Employee("Aman", "Analyst", "24000");
        Employee emp2 = new Employee("Sachin", "Developer", "39000");
        BQ.add(emp1);
        BQ.add(emp2);
  
        // printing Arraylist and queue
        System.out.println("Before drainTo():");
        System.out.println("BlockingQueue : \n"
                           + BQ.toString());
        System.out.println("ArrayList : \n"
                           + collection);
  
        // Apply drainTo method and pass collection as parameter
        int response = BQ.drainTo(collection);
  
        // print no of element passed
        System.out.println("\nNo of element passed: " + response);
  
        // printing Arraylist and queue after applying drainTo() method
        System.out.println("\nAfter drainTo():");
        System.out.println("BlockingQueue : \n"
                           + BQ.toString());
        System.out.println("ArrayList : \n"
                           + collection);
    }
}

输出。

Before drainTo():
LinkedBlockingQueue : 
[Employee [name=Aman, position=Analyst, salary=24000], Employee [name=Sachin, position=Developer, salary=39000]]
ArrayList : 
[]

No of element passed: 2

After drainTo():
LinkedBlockingQueue : 
[]
ArrayList : 
[Employee [name=Aman, position=Analyst, salary=24000], Employee [name=Sachin, position=Developer, salary=39000]]

程序2 :

// Java Program Demonstrate
// drainTo(Collection C)
// method of BlockingQueue.
  
import java.util.ArrayList;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.BlockingQueue;
  
public class GFG {
  
    public static void main(String[] args)
        throws InterruptedException
    {
        // define capacity of BlockingQueue
        int capacityOfQueue = 4;
  
        // create object of BlockingQueue
        BlockingQueue<Integer>
            BQ = new LinkedBlockingQueue<Integer>(capacityOfQueue);
  
        // add elements to queue
        BQ.put(85461);
        BQ.put(44648);
        BQ.put(45654);
  
        // create a collection with null
        ArrayList<Integer> add = null;
  
        // try to drain null queue to collection
        try {
            BQ.drainTo(add);
        }
        catch (Exception e) {
            System.out.println("Exception: " + e);
        }
    }
}

输出。

Exception: java.lang.NullPointerException

drainTo(Collection<? super E> col, int maxElements)

**drainTo(Collection <? super E> col, int maxElements) **用于转移固定数量的元素,在drainTo()中以整数形式传递给集合,集合也被作为参数传递给方法。在转移元素后,BlockingQueue只有那些没有转移到集合中的元素。这个函数和上面的函数一样,在传输固定数量的元素时有一些限制。

语法

public int drainTo(Collection<? super E> col, int maxElements)

参数: 该方法接受两个参数。

  • col – 它表示要从BlockingQueue转移元素的集合。
  • maxElements – 这是一个整数类型,指的是要转移到集合的最大元素数。

返回值: 该方法返回从队列中排入集合的元素数量。

异常: 该方法抛出以下异常。

  • UnsupportedOperationException – 如果集合不能添加元素。
  • ClassCastException – 如果元素的类别阻止方法添加元素到集合。
  • NullPointerException – 如果集合是空的。
  • IllegalArgumentException – 如果方法的参数阻止它被添加到指定的集合中。

下面的程序说明了BlockingQueue类的drainTo(Collection<? super E> col, int maxElements) 方法

程序1:

下面的程序有一个存储Employee对象的BlockingQueue,其中有一个HashSet,它将存储BlockingQueue中的所有Employee对象。所以BlockingQueue的drainTo()被用来从队列中传递一些雇员对象到ArrayList。因此,要转移的元素数量在方法中被作为参数传递。

// Java program  to demonstrate drainTo()
// method of BlockingQueue.
  
import java.util.*;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.BlockingQueue;
  
public class GFG {
  
    // create a Employee Object with
    // position and salary as attribute
    public class Employee {
  
        public String name;
        public String position;
        public String salary;
        Employee(String name, String position, String salary)
        {
            this.name = name;
            this.position = position;
            this.salary = salary;
        }
        @Override
        public String toString()
        {
            return "Employee [name=" + name + ", "
                + "position=" + position + ", salary=" + salary + "]";
        }
    }
  
    // Main Method
    public static void main(String[] args)
    {
        GFG gfg = new GFG();
        gfg.containsMethodExample();
    }
  
    public void containsMethodExample()
    {
  
        // define capacity of BlockingQueue
        int capacity = 10;
  
        // create object of BlockingQueue
        BlockingQueue<Employee> BQ
            = new LinkedBlockingQueue<Employee>(capacity);
  
        // create a HashSet to pass as parameter to drainTo()
        HashSet<Employee> collection = new HashSet<Employee>();
  
        // add Employee object to queue
        Employee emp1 = new Employee("Sachin", "Analyst", "40000");
        Employee emp2 = new Employee("Aman", "Developer", "69000");
        Employee emp3 = new Employee("Kajal", "Accountant", "39000");
        BQ.add(emp1);
        BQ.add(emp2);
        BQ.add(emp3);
  
        // printing Arraylist and queue before applying drainTo() method
        System.out.println("Before drainTo():");
        System.out.println("No of Elements in Queue is " + BQ.size());
        System.out.println("Elements in Queue is as follows");
        Iterator<Employee> listOfemp = BQ.iterator();
        while (listOfemp.hasNext())
            System.out.println(listOfemp.next());
  
        System.out.println("No of Elements in HashSet is " + collection.size());
        System.out.println("Elements in HashSet is as follows:");
        for (Employee emp : collection)
            System.out.println(emp);
  
        // Initialize no of element passed to collection
        // using drainTo() method
        int noOfElement = 2;
  
        // Apply drainTo method and pass collection as parameter
        int response = BQ.drainTo(collection, noOfElement);
  
        // print no of element passed
        System.out.println("\nNo of element passed: " + response);
  
        // printing Arraylist and queue after applying drainTo() method
        System.out.println("\nAfter drainTo():");
        System.out.println("No of Elements in Queue is " + BQ.size());
        System.out.println("Elements in Queue is as follows");
        listOfemp = BQ.iterator();
        while (listOfemp.hasNext())
            System.out.println(listOfemp.next());
  
        System.out.println("No of Elements in HashSet is " + collection.size());
        System.out.println("Elements in HashSet is as follows:");
        for (Employee emp : collection)
            System.out.println(emp);
    }
}

输出。

Before drainTo():
No of Elements in Queue is 3
Elements in Queue is as follows
Employee [name=Sachin, position=Analyst, salary=40000]
Employee [name=Aman, position=Developer, salary=69000]
Employee [name=Kajal, position=Accountant, salary=39000]
No of Elements in HashSet is 0
Elements in HashSet is as follows:

No of element passed: 2

After drainTo():
No of Elements in Queue is 1
Elements in Queue is as follows
Employee [name=Kajal, position=Accountant, salary=39000]
No of Elements in HashSet is 2
Elements in HashSet is as follows:
Employee [name=Sachin, position=Analyst, salary=40000]
Employee [name=Aman, position=Developer, salary=69000]

参考资料

  • https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/BlockingQueue.html#drainTo(java.util.Collection)
  • https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/BlockingQueue.html#drainTo(java.util.Collection, %20int)

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程