Intern — Junior
Have you had experience using queues in your projects?
sobes.tech AI
Answer from AI
Yes, in Java projects I often used queues to organize thread-safe data exchange between threads or to order tasks.
For example, the LinkedBlockingQueue class from the java.util.concurrent package allows safe addition and retrieval of elements in a multithreaded environment. This is convenient for implementing the producer-consumer pattern.
Example:
import java.util.concurrent.LinkedBlockingQueue;
LinkedBlockingQueue<String> queue = new LinkedBlockingQueue<>();
// Producer
new Thread(() -> {
try {
queue.put("Task 1");
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}).start();
// Consumer
new Thread(() -> {
try {
String task = queue.take();
System.out.println("Processing: " + task);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}).start();
Thus, queues help organize safe and ordered data exchange between threads.