Java中的LinkedBlockingDeque offer() 方法
LinkedBlockingDeque的offer(E e)方法将参数中传递的元素插入到 Deque 的末尾。如果容器的容量已超出,则它不会像 add() 和 addFirst()函数那样返回异常。
句法:
public boolean offer(E e)
参数:此方法接受一个强制参数e ,它是要插入到 LinkedBlockingDeque 末尾的元素。
返回:如果元素已被插入,此方法返回true ,否则返回false。
下面的程序说明了 LinkedBlockingDeque 的 offer() 方法:
方案一:
// Java Program Demonstrate offer()
// method of LinkedBlockingDeque
import java.util.concurrent.LinkedBlockingDeque;
import java.util.*;
public class GFG {
public static void main(String[] args)
throws IllegalStateException
{
// create object of LinkedBlockingDeque
LinkedBlockingDeque LBD
= new LinkedBlockingDeque(4);
// Add numbers to end of LinkedBlockingDeque
LBD.offer(7855642);
LBD.offer(35658786);
LBD.offer(5278367);
LBD.offer(74381793);
// Cannot be inserted
LBD.offer(10);
// cannot be inserted hence returns false
if (!LBD.offer(10))
System.out.println("The element 10 cannot be inserted"+
" as capacity is full");
// before removing print queue
System.out.println("Linked Blocking Deque: " + LBD);
}
}
输出:
The element 10 cannot be inserted as capacity is full
Linked Blocking Deque: [7855642, 35658786, 5278367, 74381793]
方案二:
// Java Program Demonstrate offer()
// method of LinkedBlockingDeque
import java.util.concurrent.LinkedBlockingDeque;
import java.util.*;
public class GFG {
public static void main(String[] args)
throws IllegalStateException
{
// create object of LinkedBlockingDeque
LinkedBlockingDeque LBD
= new LinkedBlockingDeque(4);
// Add numbers to end of LinkedBlockingDeque
LBD.offer("abc");
LBD.offer("gopu");
LBD.offer("geeks");
LBD.offer("richik");
// Cannot be inserted
LBD.offer("hii");
// cannot be inserted hence returns false
if (!LBD.offer("hii"))
System.out.println("The element 'hii' cannot be inserted"+
" as capacity is full");
// before removing print queue
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: Java/util/concurrent/LinkedBlockingDeque.html#offer(E)