LinkedTransferQueue take() method in Java
Last Updated :
14 Sep, 2018
The java.util.concurrent.LinkedTransferQueue.take() method is an in-built function in Java which retrieves and remove the first element of the queue. This method also waits (if necessary) until an element becomes available.
Syntax:
LinkedTransferQueue.take()
Parameters: The function does not accept any parameter.
Return Value: The function returns the first element of the queue.
Exceptions: The function throws InterruptedException if interrupted while waiting.
Below programs illustrate the java.util.concurrent.LinkedTransferQueue.take() :
Program 1:
import java.util.concurrent.LinkedTransferQueue;
class LinkedTransferQueueTakeExample1 {
public static void main(String[] args) throws Exception
{
LinkedTransferQueue<String> queue =
new LinkedTransferQueue<String>();
queue.add( "Alex" );
queue.add( "Bob" );
queue.add( "Chuck" );
queue.add( "Drake" );
queue.add( "Eric" );
System.out.println( "Elements are :" );
for (String xyz : queue) {
System.out.println(queue.take());
}
System.out.println( "Queue Size: " + queue.size());
}
}
|
Output:
Elements are :
Alex
Bob
Chuck
Drake
Eric
Queue Size: 0
Program 2:
import java.util.concurrent.LinkedTransferQueue;
class LinkedTransferQueueTakeExample2 {
public static void main(String[] args) throws Exception
{
LinkedTransferQueue<Integer> queue =
new LinkedTransferQueue<Integer>();
for ( int i = 1 ; i <= 5 ; i++)
queue.add(i);
System.out.println( "Elements are :" );
for (Integer xyz : queue) {
System.out.println(queue.take());
}
System.out.println( "Queue Size: " + queue.size());
}
}
|
Output:
Elements are :
1
2
3
4
5
Queue Size: 0
Reference : https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/LinkedTransferQueue.html#take()
Share your thoughts in the comments
Please Login to comment...