In this section we will discuss how can putLast(e) method be implemented in BlockingDeque interface in java.
putLast(e) method of BlockingDeque Interface in Java.
In this section we will discuss how can putLast(e) method be implemented in BlockingDeque interface in java.
Syntax
void putLast(E e)
This method inserts a specified element at the last position into the deque, to insert an element this method waits (if necessary) until the waiting time is specified for becoming the space available.
Parameter description
e : It takes an argument what do you want to insert into the deque.
Example of putLast() method
In this example we will show you how does putLast() method work in BlockingDeque interface. This example will help you to understand how can you insert a specified element at the last position into the underlying deque.
Example :
package devmanuals.com; import java.util.concurrent.BlockingDeque; import java.util.concurrent.LinkedBlockingDeque; class PutLast implements Runnable { String name; BlockingDeque<Integer> bdq; public PutLast(String name, BlockingDeque<Integer> bdq) { this.name = name; this.bdq = bdq; } public void run() { System.out.println(name + " inserted the element into the deque"); for (int i = 0; i < 5; i++) { bdq.add(i); try { Thread.sleep(400); System.out.println(i); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println("Therfore deque = " + bdq); System.out.println("Size of deque = " + bdq.size()); int j = bdq.pollFirst(); System.out.println(name+" removes the first element (" + j+ "), then remaining \n elements of deque = " + bdq + " and size = " + bdq.size()); } } class PutLast1 implements Runnable { String name; BlockingDeque<Integer> bdq; public PutLast1(String name, BlockingDeque<Integer> bdq) { this.name = name; this.bdq = bdq; } public void run() { try { Thread.sleep(1500); // Here the implementation of this method will insert // a new element into the deque. bdq.putLast(5); System.out.println(name+" Inserts a new element \n at last position then deque = "+bdq + "and size = " + bdq.size()); } catch (InterruptedException e) { e.printStackTrace(); } } } public class BdqPutLast { public static void main(String[] args) { BlockingDeque<Integer> bdq = new LinkedBlockingDeque<Integer>(5); Runnable a = new PutLast("A", bdq); Runnable b = new PutLast1("B", bdq); new Thread(a).start(); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } new Thread(b).start(); } }
Output :
A inserted the element into the deque 0 1 2 3 4 Therfore deque = [0, 1, 2, 3, 4] Size of deque = 5 A removes the first element (0), then remaining elements of deque = [1, 2, 3, 4] and size = 4 B Inserts a new element at last position then deque = [1, 2, 3, 4, 5]and size = 5 |
[ 0 ] Comments