BlockingQueue接口的add(E e)方法将在参数中传递的元素插入到Queue的末尾,如果有空间。如果BlockingQueue操作系统的容量受到限制并且没有剩余空间可插入,则它将返回IllegalStateException。
用法:
public void add(E e)
参数:此方法接受强制性参数e,该参数是要插入到BlockingQueue末尾的元素。
返回值:成功插入时此方法返回true。
异常:
IllegalStateException:如果由于容量限制此时无法添加元素
NullPointerException:如果指定的元素为null
注意:BlockingQueue的add()方法已从Java中的Queue类继承。
下面的程序说明BlockingQueue的add()方法:
示例1:
// Java Program Demonstrate add()
// method of BlockingQueue
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.BlockingQueue;
import java.util.*;
public class GFG {
public static void main(String[] args)
throws IllegalStateException
{
// create object of BlockingQueue
BlockingQueue BQ
= new LinkedBlockingDeque();
// Add numbers to the BlockingQueue
BQ.add(7855642);
BQ.add(35658786);
BQ.add(5278367);
BQ.add(74381793);
// before removing print BlockingQueue
System.out.println("Blocking Queue: " + BQ);
}
}
输出:
Blocking Queue: [7855642, 35658786, 5278367, 74381793]
示例2:
输出:
Exception in thread "main" java.lang.IllegalStateException: Deque full
at java.util.concurrent.LinkedBlockingDeque.addLast(LinkedBlockingDeque.java:335)
at java.util.concurrent.LinkedBlockingDeque.add(LinkedBlockingDeque.java:633)
at GFG.main(GFG.java:23)
示例3:
// Java Program Demonstrate add()
// method of LinkedBlockingDeque
// when null is inserted
import java.util.concurrent.LinkedBlockingDeque;
import java.util.*;
public class GFG {
public static void main(String[] args)
throws IllegalStateException
{
// create object of LinkedBlockingDeque
LinkedBlockingDeque BQ
= new LinkedBlockingDeque();
// Add numbers to end of LinkedBlockingDeque
BQ.add(7855642);
BQ.add(35658786);
BQ.add(5278367);
// NULL
BQ.add(null);
// before removing print Deque
System.out.println("Linked Blocking Deque: " + BQ);
}
}
输出:
Exception in thread "main" java.lang.IllegalStateException: Deque full
at java.util.concurrent.LinkedBlockingDeque.addLast(LinkedBlockingDeque.java:335)
at java.util.concurrent.LinkedBlockingDeque.add(LinkedBlockingDeque.java:633)
at GFG.main(GFG.java:25)