The LinkedBlockingQueue in Java is part of the java.util.concurrent package and implements the BlockingQueue interface. It provides a thread-safe, bounded, or unbounded queue used for managing tasks in a producer-consumer scenario. This queue can be used in multithreaded environments where one thread produces data that other threads consume.
- This class is thread-safe.
- The queue supports blocking operations.
- If the constructor is provided with a capacity, it becomes a bounded queue, meaning the maximum number of elements it can hold is limited.
- If no capacity is provided, the queue is unbounded and can grow as required by the number of elements added.
- The LinkedBlockingQueue follows First In First Out (FIFO) ordering for both the insertion and removal of elements.
Example: This example demonstrates how to insert elements into a LinkedBlockingQueue and print its contents.
import java.util.concurrent.LinkedBlockingQueue;
public class Geeks {
public static void main(String[] args)
throws InterruptedException
{
// Create a LinkedBlockingQueue with a capacity of 3
LinkedBlockingQueue<String> q = new LinkedBlockingQueue<>(3);
// Insert elements into the queue
q.put("Geek 1");
q.put("Geek 2");
q.put("Geek 3");
// Print the elements of the queue
System.out.println("LinkedBlockingQueue is: ");
for (String i : q) {
System.out.println(i);
}
}
}
Output
LinkedBlockingQueue is: Geek 1 Geek 2 Geek 3