Java BlockingDeque offer()函数及示例

Java BlockingDeque offer()函数及示例

BlockingDequeoffer(E e) 方法将参数中传递的元素插入到Deque的末端。如果容器的容量超过了,那么它不会像add()和addFirst()函数那样返回一个异常。

语法

public boolean offer(E e)

参数: 该方法接受一个强制性参数 e ,它是要插入BlockingDeque末端的元素。

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

注意BlockingDeque 的offer()方法已经从Java中的LinkedBlockingDeque类继承。

以下程序说明了BlockingDeque的offer()方法。

程序1 :

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

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程