import java.util.LinkedList; import java.util.Queue; public class QueueExample { public static void main(String[] args) throws InterruptedException { Queuequeue = new LinkedList<>(); queue.offer("first"); queue.offer("second"); queue.offer("third"); synchronized (queue) { while (queue.size() == 0) { queue.wait(); } String element = queue.poll(); System.out.println("Removed Element: " + element); } } }
import java.util.LinkedList; import java.util.Queue; public class QueueExample { public static void main(String[] args) throws InterruptedException { QueueThis example is similar to the first one, but with a timeout of 1 second. If the queue is still empty after 1 second, the thread will resume execution regardless of whether an element is available or not. Both the examples mentioned above use the wait() method from the java.util.Queue package from Java Standard Library.queue = new LinkedList<>(); queue.offer("first"); queue.offer("second"); queue.offer("third"); synchronized (queue) { while (queue.size() == 0) { queue.wait(1000); // wait for 1 second } String element = queue.poll(); System.out.println("Removed Element: " + element); } } }