Curriculum
LinkedBlockingQueue is a class that implements the BlockingQueue interface in Java. It is a bounded blocking queue that stores elements in a linked list. Unlike ArrayBlockingQueue, the capacity of LinkedBlockingQueue can be optionally bounded. If the capacity is not specified, it defaults to Integer.MAX_VALUE
.
Here is an example of creating a LinkedBlockingQueue object with a capacity of 5:
BlockingQueue<String> queue = new LinkedBlockingQueue<>(5);
The LinkedBlockingQueue class provides the same methods as ArrayBlockingQueue, including:
Here is an example of using a LinkedBlockingQueue to implement a producer-consumer pattern:
import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; public class ProducerConsumerExample { public static void main(String[] args) { BlockingQueue<Integer> queue = new LinkedBlockingQueue<>(5); Thread producer = new Thread(() -> { for (int i = 1; i <= 10; i++) { try { queue.put(i); System.out.println("Produced: " + i); Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } }); Thread consumer = new Thread(() -> { while (true) { try { int num = queue.take(); System.out.println("Consumed: " + num); Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } } }); producer.start(); consumer.start(); } }
In this example, the producer thread produces 10 integers and puts them into the queue using the put()
method. The consumer thread consumes the integers by taking them from the queue using the take()
method. The output shows that the producer and consumer threads are running concurrently and the producer blocks when the queue is full, and the consumer blocks when the queue is empty.