Java中BlockingDeque offerLast()方法及其示例
BlockingDeque 中的 offerLast(E e) 方法将传入参数的元素插入到Deque容器的末端。如果容器的容量已经超过,则不像add()和addLast()函数一样返回异常。
语法:
public boolean offerLast(E e)
参数:
此方法接受一个 e 参数,该参数是要插入到BlockingDeque末尾的元素。
返回值:
如果已插入元素,则返回true,否则返回false。
注: BlockingDeque 中的offerLast()方法是从Java中的LinkedBlockingDeque类继承而来。
以下程序说明了BlockingDeque的offerLast()方法:
程序1:
// Java Program Demonstrate offerLast()
// 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.offerLast(7855642);
BD.offerLast(35658786);
BD.offerLast(5278367);
BD.offerLast(74381793);
// Cannot be inserted
BD.offerLast(10);
// cannot be inserted hence returns false
if (!BD.offerLast(10))
System.out.println("The element 10 cannot be inserted"
+ " as capacity is full");
// before removing print queue
System.out.println("Blocking Deque: " + BD);
}
}
结果:元素10无法插入,因为容量已满
Blocking Deque: [7855642, 35658786, 5278367, 74381793]```
程序2:
// Java Program Demonstrate offerLast()
// 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.offerLast("abc");
BD.offerLast("gopu");
BD.offerLast("geeks");
BD.offerLast("richik");
// Cannot be inserted
BD.offerLast("hii");
// cannot be inserted hence returns false
if (!BD.offerLast("hii"))
System.out.println("The element 'hii' cannot be"
+ " inserted as capacity is full");
// before removing print queue
System.out.println("Blocking Deque: " + BD);
}
}
结果:元素'hii'无法插入,因为容量已满
Blocking Deque: [abc, gopu, geeks, richik]```
参考文献: https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/BlockingDeque.html#offerLast(E)
极客教程