Programa Java para implementar la API LinkedBlockingQueue

La API LinkedBlockingQueue es una cola limitada opcionalmente basada en Nodes vinculados. Ordena los elementos en orden FIFO (First In First Out). La cabeza de esta cola es el elemento que ha estado en la cola durante más tiempo y la cola de la cola es el elemento que ha estado en la cola menos tiempo. Los nuevos elementos se insertan al final de la cola y las operaciones de recuperación de la cola obtienen elementos al principio de la cola. Pertenece al paquete java.util.concurrent. Extiende las clases Object, AbstractCollection y AbstractQueue.

El argumento de capacidad sirve como una forma de evitar una expansión excesiva de la cola. La capacidad (si no se especifica) es igual a Integer.MAX_VALUE. Los Nodes vinculados se crean dinámicamente en cada inserción, a menos que esto haga que la cola supere su capacidad. 

La API LinkedBlockingQueue es miembro de Java Collection Framework.

Todas las interfaces implementadas:

1. Serializable
2. Iterable<E>
3. Collection<E>
4. BlockingQueue<E>
5. Queue<E>

Parámetros: E — El tipo de elementos en la colección

Sintaxis:

public class LinkedBlockingQueue<E> extends AbstractQueue<E>
implements BlockingQueue<E>, Serializable

Constructores:

  1. public LinkedBlockingQueue(): crea un LinkedBlockingQueue con una capacidad de Integer.MAX_VALUE.
  2. public LinkedBlockingQueue(Collection<? extends E> c) – Crea una LinkedBlockingQueue de capacidad Integer.MAX_VALUE, que inicialmente contiene los elementos de la colección especificada.
  3. LinkedBlockingQueue público (capacidad int): crea un LinkedBlockingQueue con la capacidad dada.

Implementación:

Ejemplo

Java

// Java Program to Implement LinkedBlockingQueue API
 
import java.util.Collection;
import java.util.Iterator;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
 
public class BlockingQueue<E> {
    private LinkedBlockingQueue<E> q;
 
    // Creates a LinkedBlockingQueue with a size of
    // Integer.MAX_VALUE.
    public BlockingQueue()
    {
        q = new LinkedBlockingQueue<E>();
    }
 
    // Creates a LinkedBlockingQueue initially containing
    // the elements of the given collection
    public BlockingQueue(Collection<? extends E> c)
    {
        q = new LinkedBlockingQueue<E>(c);
    }
 
    // Creates a LinkedBlockingQueue with the given size
    public BlockingQueue(int size)
    {
        q = new LinkedBlockingQueue<E>(size);
    }
 
    // Returns true if the queue contains the given element
    public boolean contains(Object o)
    {
        return q.contains(o);
    }
 
    // Removes all elements from the queue and adds them to
    // the given collection.
    public int drainTo(Collection<? super E> c)
    {
        return q.drainTo(c);
    }
 
    //  Removes the elements from the queue and adds them to
    //  the given collection.
    public int drainTo(Collection<? super E> c, int maxEle)
    {
        return q.drainTo(c, maxEle);
    }
 
    // Returns an iterator over the elements in the queue
    public Iterator<E> iterator() { return q.iterator(); }
 
    // removes all the elements from the queue.
    void clear() { q.clear(); }
 
    // Inserts the given element at the end of the queue,
    // returning true upon inserting and false if the queue
    // is full.
    public boolean offer(E e) { return q.offer(e); }
 
    // inserts then given element at the end and wait for
    // the given time for the space to become available
    public boolean offer(E e, long timeout, TimeUnit unit)
        throws InterruptedException
    {
        return q.offer(e, timeout, unit);
    }
 
    // Retrieves, but does not remove, the head of the
    // queue, or returns null if this queue is empty.
    public E peek() { return q.peek(); }
 
    //  Retrieves and removes the head of the queue
    public E poll() { return q.poll(); }
 
    // Retrieves and removes the head of the queue and wait
    // for the specified time for the element to become
    // available.
    public E poll(long tout, TimeUnit un)
        throws InterruptedException
    {
        return q.poll(tout, un);
    }
 
    // Returns the number of additional elements that the
    // queue can contain without blocking.
    public int remainingCapacity()
    {
        return q.remainingCapacity();
    }
 
    // Removes the specified element from the queue
    public boolean remove(Object o) { return q.remove(o); }
 
    // Returns the number of elements in the queue
    public int size() { return q.size(); }
 
    // Inserts the given element at the end of the queue,
    // wait for space to become available
    public void put(E e) throws InterruptedException
    {
        q.put(e);
    }
 
    // Retrieves and removes the head of the queue wait till
    // an element becomes available
    public E take() throws InterruptedException
    {
        return q.take();
    }
 
    // Returns an array containing all the elements in the
    // queue.
    public Object[] toArray() { return q.toArray(); }
 
    // Returns an array containing all of the elements in
    // the queue
    public <T> T[] toArray(T[] a) { return q.toArray(a); }
 
    // Returns a string representation of th collection.
    public String toString() { return q.toString(); }
 
    public static void main(String[] args)
    {
        BlockingQueue<Integer> q
            = new BlockingQueue<Integer>();
        try {
            q.put(1);
            q.put(2);
            q.put(3);
        }
        catch (InterruptedException e) {
            e.printStackTrace();
        }
 
        System.out.println(
            "The elements of the LinkedBlockingQueue is ");
 
        Iterator<Integer> i = q.iterator();
 
        while (i.hasNext()) {
            System.out.print(i.next() + "\t");
        }
        System.out.println();
 
        System.out.println("The remaining capacity is "
                           + q.remainingCapacity());
 
        System.out.println("3 removed " + q.remove(3));
 
        q.offer(6);
        q.offer(7);
 
        System.out.println(
            "The peak element of the LinkedBlockingQueue is "
            + q.peek());
 
        System.out.println(
            "The peak element of the LinkedBlockingQueue is "
            + q.poll());
 
        System.out.println(
            "The LinkedBlockingQueue contains 4 :"
            + q.contains(4));
 
        System.out.println(
            "The LinkedBlockingQueue contains 1 :"
            + q.contains(1));
 
        System.out.println(
            "The size of the LinkedBlockingQueue is "
            + q.size());
 
        System.out.println(q);
    }
}
Producción

The elements of the LinkedBlockingQueue is 
1    2    3    
The remaining capacity is 2147483644
3 removed true
The peak element of the LinkedBlockingQueue is 1
The peak element of the LinkedBlockingQueue is 1
The LinkedBlockingQueue contains 4 :false
The LinkedBlockingQueue contains 1 :false
The size of the LinkedBlockingQueue is 3
[2, 6, 7]
Producción

The elements of the LinkedBlockingQueue is 
1    2    3    
The remaining capcity is 2147483644
3 removed true
The peak element of the LinkedBlockingQueue is 1
The peak element of the LinkedBlockingQueue is 1
The LinkedBlockingQueue contains 4 :false
The LinkedBlockingQueue contains 1 :false
The size of the LinkedBlockingQueue is 3
[2, 6, 7]

Métodos:

Método Escribe Descripción
clear() vacío  Elimina todos los elementos de LinkedBlockingQueue
contiene (Objeto O) booleano Devuelve verdadero si la cola contiene el elemento especificado.
iterador() Iterador(<E>) Devuelve un iterador sobre los elementos de la cola.
oferta(E e) booleano Inserta el elemento especificado al final de esta cola si es posible y devuelve verdadero en caso de éxito, de lo contrario, falso.
oferta (E e, tiempo de espera prolongado, unidad TimeUnit) booleano Inserta el elemento especificado al final de la cola y espera el tiempo especificado para que el espacio esté disponible.
ojeada() mi Recupera, pero no elimina, la cabeza de la cola.
encuesta() mi Recupera y elimina la cabeza de la cola.
poner (E e) vacío Inserta el elemento especificado al final de esta cola, esperando si es necesario que haya espacio disponible.
capacidad restante() En t Devuelve el número de elementos adicionales que esta cola puede aceptar idealmente sin bloquearse.
Talla() En t Devuelve el tamaño de la cola.
aArray() Objeto[] Convierte la cola en una array
drenajeA(Colección<? super E> c) En t Elimina todos los elementos disponibles de la cola y los agrega a la colección especificada.
tomar() mi Recupera y elimina el encabezado de esta cola, esperando si es necesario hasta que un elemento esté disponible.
eliminar (Objeto O) booleano Elimina el elemento especificado de la cola, si está presente.

Publicación traducida automáticamente

Artículo escrito por namitachaudhary60 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *