import
java.util.Queue;
import
java.util.concurrent.ConcurrentLinkedQueue;
public
class
ThreadSafeQueueExample
{
public
static
void
main(String args[])
{
Queue<String> threadSafeQueue =
new
ConcurrentLinkedQueue<>();
threadSafeQueue.add(
"Element 1"
);
threadSafeQueue.add(
"Element 2"
);
threadSafeQueue.add(
"Element 3"
);
String element = threadSafeQueue.poll();
System.out.println(
"Removed element: "
+ element);
Runnable producer = () -> {
for
(
int
i =
0
; i <
5
; i++) {
threadSafeQueue.add(
"New Element "
+ i);
System.out.println(
"Added New Element "
+ i);
}
};
Runnable consumer = () -> {
while
(!threadSafeQueue.isEmpty()) {
String item = threadSafeQueue.poll();
System.out.println(
"Consumed: "
+ item);
}
};
Thread producerThread =
new
Thread(producer);
Thread consumerThread =
new
Thread(consumer);
producerThread.start();
consumerThread.start();
try
{
producerThread.join();
consumerThread.join();
}
catch
(InterruptedException e) {
e.printStackTrace();
}
System.out.println(
"Remaining elements in the queue: "
+ threadSafeQueue);
}
}