Challenge: Two Workers
Completed
Read n. Start two threads: one adds up 1 to n/2, the other adds up n/2 + 1 to n (n/2 is integer division). Wait for both with join(), then print each part and the total.
Input
One whole number n (2 ≤ n ≤ 1000000).
Output
Part 1: <sum> Part 2: <sum> Total: <sum>
Example
Input
10
Output
Part 1: 15 Part 2: 40 Total: 55
Editor
Java
Hints
A lambda can only use local variables that never change (n and mid are fine).
Store each thread's answer in a static field.
Use long – the total for a million is bigger than an int can hold.
Solution explanation
Each thread writes its own field, so they never fight over the same variable, and join() makes sure both are done before we print.
Show solution
import java.util.Scanner;
public class Main {
static long part1, part2;
public static void main(String[] args) throws InterruptedException {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int mid = n / 2;
Thread t1 = new Thread(() -> {
long s = 0;
for (int i = 1; i <= mid; i++) s += i;
part1 = s;
});
Thread t2 = new Thread(() -> {
long s = 0;
for (int i = mid + 1; i <= n; i++) s += i;
part2 = s;
});
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println("Part 1: " + part1);
System.out.println("Part 2: " + part2);
System.out.println("Total: " + (part1 + part2));
}
} Output
Answer
You can practice without logging in. Log in to save completion.
Save your progress
You're practising as a guest, so your progress won't be saved.
- Track every lab you complete
- Earn verifiable lab certificates
- See your progress in every module