Synchronization and locks · Topic 8 of 8
BlockingQueue (producer and consumer)
Definition​
A BlockingQueue passes work between threads safely. put waits when the queue is full and take waits when it is empty, so a producer and a consumer can run at their own speed without any manual locking.
Example code​
One producer, one consumer
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
class Demo {
public static void main(String[] args) throws InterruptedException {
BlockingQueue<Integer> queue = new ArrayBlockingQueue<>(2); // holds at most 2 items
int[] sum = {0};
Thread producer = new Thread(() -> {
try {
for (int i = 1; i <= 5; i++) queue.put(i); // waits if the queue is full
queue.put(-1); // a "stop" marker
} catch (InterruptedException ignored) { }
});
Thread consumer = new Thread(() -> {
try {
for (int item = queue.take(); item != -1; item = queue.take()) sum[0] += item; // waits if empty
} catch (InterruptedException ignored) { }
});
producer.start();
consumer.start();
producer.join();
consumer.join();
System.out.println("sum of consumed items: " + sum[0]);
}
}
// Output:
// sum of consumed items: 15
Finished this page? Track your progress (saved only in your browser).