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<Integer> BQ
= new LinkedBlockingDeque<Integer>();
// 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<Integer> BQ
= new LinkedBlockingDeque<Integer>();
// 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)
參考: https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/BlockingQueue.html#add(E)
相關用法
- Java BlockingQueue take()用法及代碼示例
- Java BlockingQueue contains()用法及代碼示例
- Java BlockingQueue put()用法及代碼示例
- Java BlockingQueue remainingCapacity()用法及代碼示例
- Java BlockingQueue offer()用法及代碼示例
- Java BlockingQueue poll()用法及代碼示例
- Java BlockingQueue drainTo()用法及代碼示例
- Java BlockingQueue remove()用法及代碼示例
- Java BlockingQueue用法及代碼示例
- Java Java lang.Long.numberOfLeadingZeros()用法及代碼示例
- Java Java lang.Long.highestOneBit()用法及代碼示例
- Java Java lang.Long.byteValue()用法及代碼示例
- Java Java lang.Long.reverse()用法及代碼示例
- Java Java.util.concurrent.RecursiveTask用法及代碼示例
注:本文由純淨天空篩選整理自gopaldave大神的英文原創作品 BlockingQueue add() in Java with examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。