📌  相关文章
📜  Java中的 ConcurrentLinkedDeque offer() 方法及示例

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

Java中的 ConcurrentLinkedDeque offer() 方法及示例

Java.util.concurrent.ConcurrentLinkedDeque.offer() 方法是Java中的一个内置方法,它将作为参数传递的指定元素插入到双端队列。

句法:

public boolean offer(E elem)

参数:该方法接受一个参数elem ,该参数指定要插入到双端队列的元素。

返回值:如果元素成功添加到双端队列中,该函数返回True ,否则返回False

异常:如果传递的参数为NULL ,该函数将抛出NullPointerException

下面的程序说明了ConcurrentLinkedDeque.offer()方法:

程序 1

// Java Program to Demonstrate offer()
// method of ConcurrentLinkedDeque
  
import java.util.concurrent.*;
  
class GFG {
    public static void main(String[] args)
    {
  
        // Creating an empty Deque
        ConcurrentLinkedDeque cld
            = new ConcurrentLinkedDeque();
  
        // Add elements into the Deque
        cld.add("Welcome");
        cld.add("To");
        cld.add("Geeks");
        cld.add("4");
        cld.add("Geeks");
  
        // Displaying the Deque
        System.out.println("ConcurrentLinkedDeque: "
                           + cld);
  
        // Insert an element using offer()
        if (cld.offer("GFG")) {
  
            // Displaying message
            System.out.println("Element Inserted");
        }
        else {
  
            // Displaying message
            System.out.println("Element not Inserted");
        }
  
        // Displaying the Deque
        System.out.println("ConcurrentLinkedDeque: "
                           + cld);
    }
}
输出:
ConcurrentLinkedDeque: [Welcome, To, Geeks, 4, Geeks]
Element Inserted
ConcurrentLinkedDeque: [Welcome, To, Geeks, 4, Geeks, GFG]
// Java Program to Demonstrate offer()
// method of ConcurrentLinkedDeque
  
import java.util.concurrent.*;
  
class GFG {
    public static void main(String[] args)
    {
  
        // Creating an empty Deque
        ConcurrentLinkedDeque cld
            = new ConcurrentLinkedDeque();
  
        // Add elements into the Deque
        cld.add("Welcome");
        cld.add("To");
        cld.add("Geeks");
        cld.add("4");
        cld.add("Geeks");
  
        // Displaying the Deque
        System.out.println("ConcurrentLinkedDeque: "
                           + cld);
  
        try {
  
            // Insert null element using offer()
            cld.offer(null);
        }
        catch (Exception e) {
            System.out.println(e);
        }
    }
}
输出:
ConcurrentLinkedDeque: [Welcome, To, Geeks, 4, Geeks]
java.lang.NullPointerException

参考: https://docs.oracle.com/javase/9/docs/api/ Java/util/concurrent/ConcurrentLinkedDeque.html#offer-E-