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.)

Data for this lab

Your program reads its data from standard input. Download the file, then give it to your program as shown below. Start with data set 1: its expected output is given.

os7-3-data-1.txt

2
5 3 10
What your program must print for os7-3-data-1.txt
consumed 5 (total 5)
consumed 3 (total 8)
consumed 10 (total 18)
Items: 3, total: 18, capacity: 2

Run your program first, then open this and compare line by line: your output must contain these lines exactly.

How to give the file to my program

Terminal (macOS, Linux, or Windows Command Prompt), after compiling:

java Main < os7-3-data-1.txt

Windows PowerShell does not understand <:

Get-Content os7-3-data-1.txt | java Main

IntelliJ IDEA: Run → Edit Configurations → Redirect input from. Or simply paste the content of the file into the console when the program waits for input.

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.