PriorityBlockingQueue take() method in Java
Last Updated :
26 Nov, 2018
The take() method of PriorityBlockingQueue returns head of the queue after removing it. If queue is empty, then this method will wait until an element becomes available.
Syntax:
public E take() throws InterruptedException
Returns: This method returns value at the head of this PriorityBlockingQueue.
Exception: This method throws InterruptedException, if interrupted while waiting for an element to become available.
Below programs illustrate take() method of PriorityBlockingQueue:
Example 1: To demonstrate take() method on PriorityBlockingQueue which contains a list of numbers.
import java.util.concurrent.PriorityBlockingQueue;
import java.util.*;
public class GFG {
public static void main(String[] args)
throws InterruptedException
{
PriorityBlockingQueue<Integer> PrioQueue
= new PriorityBlockingQueue<Integer>();
PrioQueue.put( 7855642 );
PrioQueue.put( 35658786 );
PrioQueue.put( 5278367 );
PrioQueue.put( 74381793 );
System.out.println( "Queue: " + PrioQueue);
int head = PrioQueue.take();
System.out.println( "Head of PriorityBlockingQueue"
+ " using take(): " + head);
System.out.print( "After removing head, Queue: "
+ PrioQueue);
}
}
|
Output:
Queue: [5278367, 35658786, 7855642, 74381793]
Head of PriorityBlockingQueue using take(): 5278367
After removing head, Queue: [7855642, 35658786, 74381793]
Example 2: To demonstrate take() method on PriorityBlockingQueue which contains String
import java.util.concurrent.PriorityBlockingQueue;
import java.util.*;
public class GFG {
public static void main(String[] args)
throws InterruptedException
{
PriorityBlockingQueue<String> names
= new PriorityBlockingQueue<String>();
names.add( "Geeks" );
names.add( "forGeeks" );
names.add( "A computer portal" );
System.out.println(names);
String head = names.take();
System.out.println( "Head of Queue: "
+ head);
System.out.print( "After removing head, Queue: "
+ names);
}
}
|
Output:
[A computer portal, forGeeks, Geeks]
Head of Queue: A computer portal
After removing head, Queue: [Geeks, forGeeks]
Reference: https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/PriorityBlockingQueue.html#take–
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...