BlockingQueuequeue = new LinkedBlockingQueue<>(5); queue.offer("Apple");
BlockingQueuequeue = new ArrayBlockingQueue<>(5); Thread producer = new Thread(() -> { for (int i = 0; i < 10; i++) { try { queue.offer(i); System.out.println("Produced: " + i); Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } });
BlockingQueueIn all of these examples, the BlockingQueue is created using a constructor from the java.util.concurrent package, depending on the implementation you want. The offer() method is then used to add elements to the queue, either in a producer or consumer thread. Overall, the BlockingQueue offer() method is a useful tool for implementing thread-safe queues in Java concurrent programming.queue = new ArrayBlockingQueue<>(5); Thread consumer = new Thread(() -> { while(true) { try { int num = queue.take(); System.out.println("Consumed: " + num); Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } });