當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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); 
    } 
}
輸出:
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)



相關用法


注:本文由純淨天空篩選整理自gopaldave大神的英文原創作品 BlockingDeque offerLast() method in Java with examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。