BlockingDeque的offerFirst(E e)方法将在参数中传递的元素插入Deque容器的前面。如果超出了容器的容量,则不会像add()和addFirst()函数一样返回异常。
用法:
public boolean offer(E e)
参数:此方法接受强制参数e,该参数是要在BlockingDeque前面插入的元素。
返回值:如果已插入元素,则此方法返回true,否则返回false。
注意:BlockingDeque的offerFirst()方法已从Java中的LinkedBlockingDeque类继承。
以下示例程序旨在说明LinkedBlockingDeque的offerFirst()方法:
示例1:
// Java Program Demonstrate offerFirst()
// method of BlockingDeque
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.BlockingDeque;
import java.util.*;
public class GFG {
public static void main(String[] args)
throws IllegalStateException
{
// create object of BlockingDeque
BlockingDeque<Integer> BD
= new LinkedBlockingDeque<Integer>(4);
// Add numbers to end of BlockingDeque
BD.offerFirst(7855642);
BD.offerFirst(35658786);
BD.offerFirst(5278367);
BD.offerFirst(74381793);
// Cannot be inserted
BD.offerFirst(10);
// cannot be inserted hence returns false
if (!BD.offerFirst(10))
System.out.println("The element 10 cannot be inserted"
+ " as capacity is full");
// before removing print queue
System.out.println("Blocking Deque: " + BD);
}
}
输出:
The element 10 cannot be inserted as capacity is full Blocking Deque: [74381793, 5278367, 35658786, 7855642]
示例2:
// Java Program Demonstrate offerFirst()
// method of BlockingDeque
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.BlockingDeque;
import java.util.*;
public class GFG {
public static void main(String[] args)
throws IllegalStateException
{
// create object of BlockingDeque
BlockingDeque<String> BD
= new LinkedBlockingDeque<String>(4);
// Add numbers to end of BlockingDeque
BD.offerFirst("abc");
BD.offerFirst("gopu");
BD.offerFirst("geeks");
BD.offerFirst("richik");
// Cannot be inserted
BD.offerFirst("hii");
// cannot be inserted hence returns false
if (!BD.offerFirst("hii"))
System.out.println("The element 'hii' cannot be"
+ " inserted as capacity is full");
// before removing print queue
System.out.println("Blocking Deque: " + BD);
}
}
输出:
The element 'hii' cannot be inserted as capacity is full Blocking Deque: [richik, geeks, gopu, abc]
参考: https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/BlockingDeque.html#offerFirst(E)
相关用法
- Java BlockingDeque take()用法及代码示例
- Java BlockingDeque put()用法及代码示例
- Java BlockingDeque add()用法及代码示例
- Java BlockingDeque contains()用法及代码示例
- Java BlockingDeque takeLast()用法及代码示例
- Java BlockingDeque iterator()用法及代码示例
- Java BlockingDeque removeLastOccurrence()用法及代码示例
- Java BlockingDeque takeFirst()用法及代码示例
- Java BlockingDeque element()用法及代码示例
- Java BlockingDeque remove()用法及代码示例
- Java BlockingDeque offerLast()用法及代码示例
- Java BlockingDeque poll()用法及代码示例
- Java BlockingDeque pollFirst()用法及代码示例
- Java BlockingDeque pollLast()用法及代码示例
- Java BlockingDeque push()用法及代码示例
注:本文由纯净天空筛选整理自gopaldave大神的英文原创作品 BlockingDeque offerFirst() method in Java with Examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。