Java中的LinkedBlockingDeque offer()方法
LinkedBlockingDeque 的 offer(E e) 方法将传递的元素插入到Deque的末尾。如果容器的容量超过了限制,则不像add()和addFirst()函数一样抛出异常。
语法:
public boolean offer(E e)
参数: 此方法接受一个必需的参数 e ,它是要插入到LinkedBlockingDeque末尾的元素。
返回值: 如果已插入元素,则此方法返回true,否则返回false。
下面的程序说明了LinkedBlockingDeque的offer()方法:
程序1:
// Java程序演示LinkedBlockingDeque offer()方法
import java.util.concurrent.LinkedBlockingDeque;
import java.util.*;
public class GFG {
public static void main(String[] args)
throws IllegalStateException
{
//创建LinkedBlockingDeque对象
LinkedBlockingDeque<Integer> LBD
= new LinkedBlockingDeque<Integer>(4);
//将数字添加到LinkedBlockingDeque的末尾
LBD.offer(7855642);
LBD.offer(35658786);
LBD.offer(5278367);
LBD.offer(74381793);
//无法插入
LBD.offer(10);
//无法插入,因此返回false
if (!LBD.offer(10))
System.out.println("The element 10 cannot be inserted"+
" as capacity is full");
//移除前打印队列
System.out.println("Linked Blocking Deque: " + LBD);
}
}
The element 10 cannot be inserted as capacity is full
Linked Blocking Deque: [7855642, 35658786, 5278367, 74381793]
程序2:
// Java程序演示LinkedBlockingDeque offer()方法
import java.util.concurrent.LinkedBlockingDeque;
import java.util.*;
public class GFG {
public static void main(String[] args)
throws IllegalStateException
{
//创建LinkedBlockingDeque对象
LinkedBlockingDeque<String> LBD
= new LinkedBlockingDeque<String>(4);
//将数字添加到LinkedBlockingDeque的末尾
LBD.offer("abc");
LBD.offer("gopu");
LBD.offer("geeks");
LBD.offer("richik");
//无法插入
LBD.offer("hii");
//无法插入,因此返回false
if (!LBD.offer("hii"))
System.out.println("The element 'hii' cannot be inserted"+
" as capacity is full");
//移除前打印队列
System.out.println("Linked Blocking Deque: " + LBD);
}
}
The element 'hii' cannot be inserted as capacity is full
Linked Blocking Deque: [abc, gopu, geeks, richik]
参考: https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/LinkedBlockingDeque.html#offer(E)
极客教程