Java BlockingDeque offerLast()方法及示例
BlockingDeque 的 offerLast(E e) 方法在Deque容器的末端插入参数中传递的元素。如果容器的容量超过了,那么它不会像add()和addLast()函数那样返回一个异常。
语法
public boolean offerLast(E e)
参数: 该方法接受一个强制性参数 e ,它是要插入BlockingDeque末端的元素。
返回: 如果元素已经被插入,该方法返回真,否则返回假。
注意 : 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);
}
}
输出。
The element 10 cannot be inserted as capacity is full
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);
}
}
输出。
The element 'hii' cannot be inserted as capacity is full
Blocking Deque: [abc, gopu, geeks, richik]
**参考资料: **https: //docs.oracle.com/javase/7/docs/api/java/util/concurrent/BlockingDeque.html#offerLast(E)