rava2
home
documentation
examples
// retoor <retoor@molodetz.nl> public class Main { static long sum1 = 0; static long sum2 = 0; static long sum3 = 0; static long sum4 = 0; public static void main(String[] args) { System.out.println("=== Parallel Sum Computation ===\n"); int n = 1000; System.out.println("Computing sum of 1 to " + n + " using 4 threads\n"); Thread t1 = new Thread(() -> { computeSum(1, 250, 1); }); Thread t2 = new Thread(() -> { computeSum(251, 500, 2); }); Thread t3 = new Thread(() -> { computeSum(501, 750, 3); }); Thread t4 = new Thread(() -> { computeSum(751, 1000, 4); }); long startTime = System.currentTimeMillis(); t1.start(); t2.start(); t3.start(); t4.start(); t1.join(); t2.join(); t3.join(); t4.join(); long endTime = System.currentTimeMillis(); System.out.println("\nPartial sums:"); System.out.println(" Thread-1 (1-250): " + sum1); System.out.println(" Thread-2 (251-500): " + sum2); System.out.println(" Thread-3 (501-750): " + sum3); System.out.println(" Thread-4 (751-1000): " + sum4); long total = sum1 + sum2 + sum3 + sum4; long expected = (long)n * (n + 1) / 2; System.out.println("\nTotal: " + total); System.out.println("Expected: " + expected); System.out.println("Match: " + (total == expected)); System.out.println("Time: " + (endTime - startTime) + "ms"); } static void computeSum(int start, int end, int threadNum) { System.out.println("[Thread-" + threadNum + "] Computing " + start + " to " + end); long sum = 0; for (int i = start; i <= end; i++) { sum += i; } if (threadNum == 1) sum1 = sum; else if (threadNum == 2) sum2 = sum; else if (threadNum == 3) sum3 = sum; else if (threadNum == 4) sum4 = sum; System.out.println("[Thread-" + threadNum + "] Result: " + sum); } }
run program
ready