Java中的 BlockingDeque put() 方法及示例
BlockingDeque的put(E e)方法将指定元素插入到这个双端队列所代表的队列中(换句话说,在这个双端队列的尾部)。如果双端队列容量受限,那么它将等待空间可用。
句法:
public void put(E e)
参数:此方法接受一个强制参数e ,它是要插入到 BlockingDeque 末尾的元素。
返回:此方法不返回任何内容。
异常:程序抛出两个异常,如下所示:
- NullPointerException – 如果指定元素为 null
- InterruptedException – 如果在等待时被中断
注意: BlockingDeque的 put() 方法继承自Java中的 LinkedBlockingDeque 类。
下面的程序说明了 BlockingDeque 的 put() 方法:
方案一:
// Java Program Demonstrate put()
// 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 InterruptedException
{
// create object of BlockingDeque
BlockingDeque BD
= new LinkedBlockingDeque();
// Add numbers to end of BlockingDeque
BD.put(7855642);
BD.put(35658786);
BD.put(5278367);
BD.put(74381793);
// print Deque
System.out.println("Blocking Deque: " + BD);
}
}
输出:
Blocking Deque: [7855642, 35658786, 5278367, 74381793]
方案二:
// Java Program Demonstrate put()
// method of BlockingDeque
// throwing NullPointerException
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.BlockingDeque;
import java.util.*;
public class GFG {
public static void main(String[] args)
throws InterruptedException
{
// create object of BlockingDeque
BlockingDeque BD
= new LinkedBlockingDeque();
// Add numbers to end of BlockingDeque
BD.put(7855642);
BD.put(35658786);
BD.put(5278367);
// throws an exception
BD.put(null);
// print Dequeue
System.out.println("Blocking Deque: " + BD);
}
}
输出:
Exception in thread "main" java.lang.NullPointerException
at java.util.concurrent.LinkedBlockingDeque.putLast(LinkedBlockingDeque.java:390)
at java.util.concurrent.LinkedBlockingDeque.put(LinkedBlockingDeque.java:649)
at GFG.main(GFG.java:24)
方案 3:
// Java Program Demonstrate put()
// method of BlockingDeque
// when capacity exceeded
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.BlockingDeque;
import java.util.*;
public class GFG {
public static void main(String[] args)
throws InterruptedException
{
// create object of BlockingDeque
BlockingDeque BD
= new LinkedBlockingDeque(3);
// Add numbers to end of BlockingDeque
BD.put(7855642);
BD.put(35658786);
BD.put(5278367);
// throws an exception
BD.put(4356789);
// print Dequeue
System.out.println("Blocking Deque: " + BD);
}
}
输出:
Max real time limit exceeded due to either by heavy load on server or by using sleep function
参考: https: Java/util/concurrent/BlockingDeque.html#put(E)