THINK FIRST·CODE LATER

← All labs

Producer–consumer with a real BlockingQueue

Problem

Use real Java threads: one producer thread reads numbers from the input and puts them into an ArrayBlockingQueue<Integer> of capacity cap; one consumer thread takes them and processes them.

Input: first line cap, then integers until the end of input (read them in the main thread first; the producer thread puts them into the queue in order). To stop, the producer puts a special end marker (use Integer.MIN_VALUE, which never appears in the input).

The consumer keeps a running total and, for each item, prints consumed X (total T). After the end marker, the main thread waits for both threads (join) and prints Items: n, total: T, max queue size seen by producer: M where M is the largest queue.size() observed by the producer right after each put — but since that value depends on timing, print instead the deterministic capacity: cap.

Output format:

consumed 5 (total 5)
consumed 3 (total 8)
consumed 10 (total 18)
Items: 3, total: 18, capacity: 2

(With one producer and one consumer, a FIFO queue guarantees this order regardless of timing.)

Write it here or in your IDE, then paste it. Compile and test it yourself before comparing. Your code stays in your browser — it is never sent to or stored on the server.