Java中的 BlockingDeque takeFirst() 方法及示例
BlockingDeque的takeFirst()方法返回并从中删除 Deque 容器的第一个元素,必要时等待直到元素可用。如果在等待时被中断,该方法将抛出InterruptedException 。
句法:
public E takeFirst()
返回:此方法返回 Deque 容器的第一个元素,如有必要,等待元素可用。
Exception :如果函数在等待时被中断,则会抛出InterruptedException 。
注意: BlockingDeque的takeFirst()方法继承自Java中的 LinkedBlockingDeque 类。
下面的程序说明了 LinkedBlockingDeque 的 takeFirst() 方法:
方案一:
// Java Program to demonstrate takeFirst()
// method of BlockingDeque
import java.util.concurrent.BlockingDeque;
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.add(7855642);
BD.add(35658786);
BD.add(5278367);
BD.add(74381793);
// print Deque
System.out.println("Blocking Deque: " + BD);
// removes the front element and prints it
System.out.println("Head of Blocking Deque: "
+ BD.takeFirst());
// prints the Deque
System.out.println("Blocking Deque: " + BD);
}
}
输出:
Blocking Deque: [7855642, 35658786, 5278367, 74381793]
Head of Linked Deque: 7855642
Blocking Deque: [35658786, 5278367, 74381793]
程序2:演示InterruptedException
// Java Program to demonstrate takeFirst()
// 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.add(7855642);
BD.add(35658786);
BD.add(5278367);
BD.add(74381793);
// print Dequeue
System.out.println("Blocking Deque: " + BD);
BD.clear();
// throws error as the list is empty and it
// is interrupted while waiting
System.out.println("Head of Blocking Deque: "
+ BD.takeFirst());
}
}
运行时错误:
Max real time limit exceeded due to either by heavy load on server or by using sleep function
参考: https: Java/util/concurrent/BlockingDeque.html#takeFirst()