THINK FIRST·CODE LATER

← All labs

Threads in practice: a parallel sum with a thread pool

Problem

Use real Java threads to sum a large array in parallel — the way an EdgeCampus analytics server splits work across cores.

Input: first line n t (number of values, number of worker tasks), then n integers (each fits in an int; the total fits in a long).

Split the array into t contiguous chunks as evenly as possible: chunk sizes differ by at most one, and the first n % t chunks get one extra element. Submit one task per chunk to an ExecutorService with a fixed pool of min(t, 4) threads, and collect the results with Future.get() in chunk order.

Print one line per chunk: chunk k [from..to]: sum (indices inclusive, 0-based; a chunk may be empty: then print chunk k [empty]: 0), then Total: T and Check: OK if T equals a sequential sum, otherwise Check: MISMATCH.

Input:

10 3
1 2 3 4 5 6 7 8 9 10

Output:

chunk 0 [0..3]: 10
chunk 1 [4..6]: 18
chunk 2 [7..9]: 27
Total: 55
Check: OK

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.