In this section we will discuss how can take() method be implemented in BlockingDeque interface in java. to retrieve and remove this method waits (if required) until the element becomes available. This method is similar to the takeFirst() method. It throws an 'InterruptedException'.
take() method of BlockingDeque Interface in Java.
In this section we will discuss how can take() method be implemented in BlockingDeque interface in java.
Syntax
E take()
This method finds and removes the first position element from the underlying deque, to retrieve and remove this method waits (if required) until the element becomes available. This method is similar to the takeFirst() method. It throws an 'InterruptedException'.
Parameter Description
This method has no parameter.
Example of take() method
In this example we will show you how does take() method work in BlockingDeque interface. This example will help you to understand how can you retrieve and remove the head element from the underlying deque.
Example :
package devmanuals.com; import java.util.concurrent.BlockingDeque; import java.util.concurrent.LinkedBlockingDeque; class Take implements Runnable { BlockingDequebdq; String name; public Take(String name, BlockingDeque bdq) { this.bdq = bdq; this.name = name; } public void run() { int i; System.out.println(name + " inserted the element into the deque"); for (i = 0; i < 5; i++) { bdq.add(i); System.out.println(i); try { Thread.sleep(400); } catch (InterruptedException e) { e.printStackTrace(); } } } } class Take1 implements Runnable { String name; BlockingDeque bdq; public Take1(String name, BlockingDeque bdq) { this.bdq = bdq; this.name = name; new Thread().start(); } public void run() { try { //Implementation of the method int j = bdq.take(); Thread.sleep(1500); System.out.println(name + " deleted the first element then remaining deque = " + bdq); System.out.println("The deleted element is = "+j); System.out.println("Size of remaining deque = "+bdq.size()); } catch (InterruptedException e) { e.printStackTrace(); } } } public class BdqTake { public static void main(String args[]) { BlockingDeque bdq = new LinkedBlockingDeque (5); Runnable a = new Take("A", bdq); new Thread(a).start(); try { Thread.sleep(400); } catch (InterruptedException e) { e.printStackTrace(); } Runnable b = new Take1("B", bdq); new Thread(b).start(); } }
Output :
A inserted the element into the deque 0 1 2 3 4 B deleted the first element then remaining deque = [1, 2, 3, 4] The deleted element is = 0 Size of remaining deque = 4 |
[ 0 ] Comments