📌  相关文章
📜  Java中的 LinkedBlockingDeque offerLast() 方法

📅  最后修改于: 2022-05-13 01:54:52.949000             🧑  作者: Mango

Java中的 LinkedBlockingDeque offerLast() 方法

LinkedBlockingDeque 的offerLast (E e)方法将参数中传入的元素插入到 Deque 容器的末尾。如果容器的容量已超出,则它不会像 add() 和 addLast()函数那样返回异常。

句法:

public boolean offerLast(E e)

参数:此方法接受一个强制参数e ,它是要插入到 LinkedBlockingDeque 末尾的元素。

返回:如果元素已被插入,此方法返回true ,否则返回false。

下面的程序说明了 LinkedBlockingDeque 的 offerLast() 方法:

方案一:

// Java Program Demonstrate offerLast()
// 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.offerLast(7855642);
        LBD.offerLast(35658786);
        LBD.offerLast(5278367);
        LBD.offerLast(74381793);
  
        // Cannot be inserted
        LBD.offerLast(10);
  
        // cannot be inserted hence returns false
        if (!LBD.offerLast(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 offerLast()
// 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.offerLast("abc");
        LBD.offerLast("gopu");
        LBD.offerLast("geeks");
        LBD.offerLast("richik");
  
        // Cannot be inserted
        LBD.offerLast("hii");
  
        // cannot be inserted hence returns false
        if (!LBD.offerLast("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#offerLast(E)