📌  相关文章
📜  Java中的 PriorityBlockingQueue put() 方法

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

Java中的 PriorityBlockingQueue put() 方法

PriorityBlockingQueueput(E e)方法用于将元素添加到此队列中。此方法将指定元素插入此优先级队列。由于队列是无界的,所以这个方法永远不会被阻塞。
句法:

public void put(E e)

参数:此方法接受一个强制参数e ,它是要插入 PriorityBlockingQueue 的元素。
返回值:该方法不返回任何内容。
异常:此方法抛出以下异常:

  • ClassCastException – 如果指定的元素无法根据优先级队列的顺序与当前在优先级队列中的元素进行比较。
  • NullPointerException – 如果指定元素为空。

下面的程序说明了 PriorityBlockingQueue 中的 put() 方法:
方案一:

Java
// Java Program Demonstrate put(E e)
// method of PriorityBlockingQueue
 
import java.util.concurrent.PriorityBlockingQueue;
 
public class GFG {
    public static void main(String[] args)
    {
 
        // create object of PriorityBlockingQueue
        PriorityBlockingQueue pbq
            = new PriorityBlockingQueue();
 
        // Add element using put() method
        pbq.put(1);
        pbq.put(2);
        pbq.put(3);
        pbq.put(4);
 
        // print elements of queue
        System.out.println("Queue: " + pbq);
    }
}


Java
// Java Program Demonstrate put(E e)
// method of PriorityBlockingQueue
 
import java.util.concurrent.PriorityBlockingQueue;
 
public class GFG {
    public static void main(String[] args)
    {
 
        // create object of PriorityBlockingQueue
        PriorityBlockingQueue pbq
            = new PriorityBlockingQueue();
 
        // try to put null value in put method
        try {
            pbq.put(null);
        }
        catch (Exception e) {
            // print error details
            System.out.println("Exception: " + e);
        }
    }
}


输出:
Queue: [1, 2, 3, 4]

程序2:演示NullPointerException

Java

// Java Program Demonstrate put(E e)
// method of PriorityBlockingQueue
 
import java.util.concurrent.PriorityBlockingQueue;
 
public class GFG {
    public static void main(String[] args)
    {
 
        // create object of PriorityBlockingQueue
        PriorityBlockingQueue pbq
            = new PriorityBlockingQueue();
 
        // try to put null value in put method
        try {
            pbq.put(null);
        }
        catch (Exception e) {
            // print error details
            System.out.println("Exception: " + e);
        }
    }
}
输出:
Exception: java.lang.NullPointerException