Java中的ConcurrentLinkedQueue add() 方法
ConcurrentLinkedQueue 的 add() 方法用于将作为参数传递给ConcurrentLinkedQueue的add()方法的元素插入到这个ConcurrentLinkedQueue的尾部。如果插入成功,则此方法返回True。ConcurrentLinkedQueue是无界的,因此此方法永远不会抛出IllegalStateException或返回false。
语法:
public boolean add(E e)
参数: 这个方法接受一个单一参数 e ,它表示要插入到这个ConcurrentLinkedQueue中的元素。
返回值: 此方法在元素成功插入后返回true。
异常: 如果指定的元素为null,则此方法会抛出 NullPointerException 。
下面的程序说明了 ConcurrentLinkedQueue 的 add() 方法:
示例 1: 演示用于添加字符串的 ConcurrentLinkedQueue add() 方法。
//Java程序演示 ConccurentLinkedQueue
// add() 方法
import java.util.concurrent.*;
public class GFG {
public static void main(String[] args)
{
// 创建ConcurrentLinkedQueue
ConcurrentLinkedQueue<String> queue = new ConcurrentLinkedQueue<String>();
// 添加字符串到队列
queue.add("Kolkata");
queue.add("Patna");
queue.add("Delhi");
queue.add("Jammu");
// 显示现有的ConcurrentLinkedQueue
System.out.println("ConcurrentLinkedQueue: " + queue);
}
}
ConcurrentLinkedQueue: [Kolkata, Patna, Delhi, Jammu]
示例 2: 演示用于添加数字的 ConcurrentLinkedQueue add() 方法。
// Java程序演示ConccurentLinkedQueue
// add() 方法
import java.util.concurrent.*;
public class GFG {
public static void main(String[] args)
{
// 创建ConcurrentLinkedQueue
ConcurrentLinkedQueue<Integer> queue = new ConcurrentLinkedQueue<Integer>();
// 向队列添加数字
queue.add(4353);
queue.add(7824);
queue.add(78249);
queue.add(8724);
// 显示现有的ConcurrentLinkedQueue
System.out.println("ConcurrentLinkedQueue: " + queue);
}
}
ConcurrentLinkedQueue: [4353, 7824, 78249, 8724]
示例 3: 演示添加Null时 add() 方法引发的 NullPointerException 。
//Java程序演示ConccurentLinkedQueue
//add() 方法
import java.util.concurrent.*;
public class GFG {
public static void main(String[] args)
{
// 创建ConcurrentLinkedQueue
ConcurrentLinkedQueue<Integer> queue = new ConcurrentLinkedQueue<Integer>();
// 向队列添加Null
try {
queue.add(null);
}
catch (NullPointerException e) {
System.out.println("在添加Null时引发异常: " + e);
}
}
}
Exception thrown while adding null: java.lang.NullPointerException
引用: https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ConcurrentLinkedQueue.html#add-E-
极客教程