📌  相关文章
📜  Java中的 BlockingQueue add() 示例

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

Java中的 BlockingQueue add() 示例

BlockingQueue接口的add(E e)方法将参数中传入的元素插入到队列的末尾,如果有空间。如果 BlockingQueue 操作系统的容量受到限制并且没有空间可供插入,则返回IllegalStateException

句法:

public void add(E e)

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

返回:此方法在成功插入时返回 true。

例外:

  • IllegalStateException : 如果此时由于容量限制无法添加元素
  • NullPointerException : 如果指定元素为 null

注意BlockingQueueadd()方法继承自Java中的Queue类。
下面的程序说明了 BlockingQueue 的 add() 方法:

方案一:

Java
// Java Program Demonstrate add()
// method of BlockingQueue
 
import java.util.*;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingDeque;
 
public class GFG {
    public static void main(String[] args)
        throws IllegalStateException
    {
 
        // create object of BlockingQueue
        BlockingQueue BQ
            = new LinkedBlockingDeque();
 
        // Add numbers to the BlockingQueue
        BQ.add(7855642);
        BQ.add(35658786);
        BQ.add(5278367);
        BQ.add(74381793);
 
        // before removing print BlockingQueue
        System.out.println("Blocking Queue: " + BQ);
    }
}


Java
// Java Program Demonstrate add()
// method of LinkedBlockingDeque
// when null is inserted
 
import java.util.*;
import java.util.concurrent.LinkedBlockingDeque;
 
public class GFG {
    public static void main(String[] args)
        throws IllegalStateException
    {
 
        // create object of LinkedBlockingDeque
        LinkedBlockingDeque BQ
            = new LinkedBlockingDeque();
 
        // Add numbers to end of LinkedBlockingDeque
        BQ.add(7855642);
        BQ.add(35658786);
        BQ.add(5278367);
 
        // NULL
        BQ.add(null);
 
        // before removing print Deque
        System.out.println("Linked Blocking Deque: " + BQ);
    }
}


输出
Blocking Queue: [7855642, 35658786, 5278367, 74381793]

方案二:

Java

// Java Program Demonstrate add()
// method of LinkedBlockingDeque
// when null is inserted
 
import java.util.*;
import java.util.concurrent.LinkedBlockingDeque;
 
public class GFG {
    public static void main(String[] args)
        throws IllegalStateException
    {
 
        // create object of LinkedBlockingDeque
        LinkedBlockingDeque BQ
            = new LinkedBlockingDeque();
 
        // Add numbers to end of LinkedBlockingDeque
        BQ.add(7855642);
        BQ.add(35658786);
        BQ.add(5278367);
 
        // NULL
        BQ.add(null);
 
        // before removing print Deque
        System.out.println("Linked Blocking Deque: " + BQ);
    }
}

输出:

Exception in thread "main" java.lang.IllegalStateException: Deque full
    at java.util.concurrent.LinkedBlockingDeque.addLast(LinkedBlockingDeque.java:335)
    at java.util.concurrent.LinkedBlockingDeque.add(LinkedBlockingDeque.java:633)
    at GFG.main(GFG.java:25)

参考: https: Java/util/concurrent/BlockingQueue.html#add(E)