Java中的BlockingQueue drainTo() 方法及其示例

Java中的BlockingQueue drainTo() 方法及其示例

drainTo(Collection col) 方法从本LinkedBlockingQueue中删除所有可用元素并将它们添加到作为参数传递的给定集合中。

注意: Java中的 BlockingQueue 类中继承了 Queue 类的 drainTo() 方法。

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 – 如果集合为null
  • IllegalArgumentException – 如果方法的参数防止将它添加到指定的集合中

以下是BlockingQueue类的drainTo()方法的示例程序:

程序1:

// Java程序演示BlockingQueue的 drainTo(Collection c)方法。

import java.util.ArrayList;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.BlockingQueue;
  
public class GFG {
  
    // 创建一个带有职位和薪水属性的Employee对象
    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 + "]";
        }
    }
  
    // 主方法
    public static void main(String[] args)
    {
        GFG gfg = new GFG();
        gfg.containsMethodExample();
    }
  
    public void containsMethodExample()
    {
  
        // 定义BlockingQueue容量
        int capacity = 50;
  
        // 创建BlockingQueue对象
        BlockingQueue<Employee> BQ
            = new LinkedBlockingQueue<Employee>(capacity);
  
        // 创建一个ArrayList作为drainTo()方法的参数
        ArrayList<Employee> collection = new ArrayList<Employee>();
  
        // 将Employee对象添加到队列中
        Employee emp1 = new Employee("Aman", "分析师", "24000");
        Employee emp2 = new Employee("Sachin", "开发人员", "39000");
        BQ.add(emp1);
        BQ.add(emp2);
  
        // 打印ArrayList和队列
        System.out.println("调用drainTo()方法之前:");
        System.out.println("BlockingQueue : \n"
                           + BQ.toString());
        System.out.println("ArrayList : \n"
                           + collection);
  
        // 调用drainTo()方法并将collection作为参数传递
        int response = BQ.drainTo(collection);
  
        // 打印传递的元素数量
        System.out.println("\n传递的元素数量: " + response);
  
        // 打印调用drainTo()方法之后的ArrayList和队列
        System.out.println("\n调用drainTo()方法之后:");
        System.out.println("BlockingQueue : \n"
                           + BQ.toString());
        System.out.println("ArrayList : \n"
                           + collection);
    }
}

调用drainTo()方法之前:
BlockingQueue :
[Employee [name=Aman, position=分析师, salary=24000], Employee [name=Sachin, position=开发人员, salary=39000]]
ArrayList :
[]

传递的元素数量: 2

调用drainTo()方法之后:
BlockingQueue :
[]
ArrayList :
[Employee [name=Aman, position=分析师, salary=24000], Employee [name=Sachin, position=开发人员, salary=39000]]

程序2:

// Java程序演示
// drainTo(Collection C)
// 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
    {
        // 定义BlockingQueue的容量
        int capacityOfQueue = 4;
  
        // 创建BlockingQueue对象
        BlockingQueue<Integer>
            BQ = new LinkedBlockingQueue<Integer>(capacityOfQueue);
  
        // 向队列添加元素
        BQ.put(85461);
        BQ.put(44648);
        BQ.put(45654);
  
        // 创建一个带有null值的集合
        ArrayList<Integer> add = null;
  
        // 尝试将null队列传递到集合
        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 – 如果集合为null
  • IllegalArgumentException – 如果方法的参数阻止它被添加到指定的集合中

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

程序1:

以下程序具有存储Employee对象的BlockingQueue,其中有一个HashSet,其中将从BlockingQueue中存储所有employee对象。因此,使用BlockingQueue的drainTo()将一些employee从队列传递到ArrayList中。因此,要传输的元素数量作为参数传递给方法。

// Java程序来演示BlockingQueue的drainTo()方法。
  
import java.util.*;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.BlockingQueue;
  
public class GFG {
  
    // 创建一个具有职位和薪资属性的Employee对象
    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 + "]";
        }
    }
  
    // 主方法
    public static void main(String[] args)
    {
        GFG gfg = new GFG();
        gfg.containsMethodExample();
    }
  
    public void containsMethodExample()
    {
  
        // 定义阻塞队列的容量
        int capacity = 10;
  
        // 创建阻塞队列对象
        BlockingQueue<Employee> BQ
            = new LinkedBlockingQueue<Employee>(capacity);
  
        // 创建一个HashSet作为drainTo()方法的参数
        HashSet<Employee> collection = new HashSet<Employee>();
  
        // 将Employee对象添加到队列中
        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);
  
        // 在应用drainTo()方法之前打印Arraylist和队列
        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);
  
        // 使用drainTo()方法初始化传递给collection的元素数量
        int noOfElement = 2;
  
        // 应用drainTo方法并将collection作为参数传递
        int response = BQ.drainTo(collection, noOfElement);
  
        // 打印传递的元素数量
        System.out.println("\nNo of element passed: " + response);
  
        // 在应用drainTo()方法之后打印Arraylist和队列
        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);
    }
}

在 drainTo() 之前: 队列中的元素数为 3 队列中的元素如下: Employee [name=Sachin,position=Analyst,salary=40000] Employee [name=Aman,position=Developer,salary=69000] Employee [name=Kajal,position=Accountant,salary=39000] 哈希集合中的元素数为 0 哈希集合中的元素如下: 传递的元素数:2 在 drainTo() 之后: 队列中的元素数为 1 队列中的元素如下: Employee [name=Kajal,position=Accountant,salary=39000] 哈希集合中的元素数为 2 哈希集合中的元素如下: Employee [name=Sachin,position=Analyst,salary=40000] Employee [name=Aman,position=Developer,salary=69000]

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程