Wednesday, 17 September 2014

LinkedBlockingDeque

It is An optionally-bounded blocking deque based on linked nodes. It provides below constructors to instantiate LinkedBlockingDeque.

public LinkedBlockingDeque()
Creates a LinkedBlockingDeque with a capacity of Integer.MAX_VALUE

public LinkedBlockingDeque(int capacity)
Creates a LinkedBlockingDeque with the given capacity.

public LinkedBlockingDeque(Collection<? extends E> c)
Creates a LinkedBlockingDeque with a capacity of Integer.MAX_VALUE, initially containing the elements of the given collection. The elements in the collection are added based on iterator.

import java.util.concurrent.BlockingDeque;
import java.util.logging.Level;
import java.util.logging.Logger;

public class Producer implements Runnable{
    BlockingDeque<Integer> queue;
    
    Producer(BlockingDeque q){
        queue = q;
    }
    
    @Override
    public void run(){
        int i=0;
        while(true){
            i++;
            try {
                queue.put(i);
                System.out.println("Producer :"+  i);
            } catch (InterruptedException ex) {
                Logger.getLogger(Producer.class.getName()).log(Level.SEVERE, null, ex);
            }
            
        }
    }
}

import java.util.concurrent.BlockingDeque;
import java.util.logging.Level;
import java.util.logging.Logger;

public class Consumer implements Runnable{
    BlockingDeque<Integer> queue;
    
    Consumer(BlockingDeque q){
        queue = q;
    }
    
    @Override
    public void run(){
        while(true){
            try {
                Thread.sleep(1000);
                System.out.println("Consumer : " + queue.take());
            } catch (InterruptedException ex) {
                Logger.getLogger(Consumer.class.getName()).log(Level.SEVERE, null, ex);
            }
     
        }
    }
}

import java.util.concurrent.BlockingDeque;
import java.util.concurrent.LinkedBlockingDeque;

public class BlockingDequeEx {
    public static void main(String args[]){
        BlockingDeque<Integer> q;
        
        q = new LinkedBlockingDeque<> (5);
        
        Producer p1 = new Producer(q);
        
        Consumer con = new Consumer(q);
        
        Thread t1 = new Thread(p1);        
        Thread t2 = new Thread(con);
        
        t1.start();
        t2.start();     
    }
}

Output
Producer :1
Producer :2
Producer :3
Producer :4
Producer :5
Consumer : 1
Producer :6
Consumer : 2
Producer :7
Consumer : 3
Producer :8





Prevoius                                                 Next                                                 Home

No comments:

Post a Comment