I am a Beginner here. I want to make comparison of runTime between the sequential and parallel (multithreading) summation of numbers from 0 to 2999999 in Java. I want to make sure myself that parallel sum is faster than sequential. I made a small program in Eclipse. However, I could not properly extract the results from threads and/or put them into the ArrayList to further sum them to have totalSum. My codes are attached. Please, help? Thank you in advance!
Here is the main class:
public class threading_sum {
public static void main(String[] args) {
//Sequential summation:
double sum_seq = 0;
long beginTime_seq = System.currentTimeMillis();
for (int i = 0; i <= 2999999; i++) {
sum_seq += i;
}
long endTime_seq = System.currentTimeMillis();
System.out.println("Sequential sum took "+(endTime_seq-beginTime_seq)+" ms. Sum is "+sum_seq);
//Parallel summation with 3 threads:
long beginTime_par = System.currentTimeMillis();
runnable R1 = new runnable(0, 999999, "Thread-1");
R1.start();
runnable R2 = new runnable(1000000, 1999999, "Thread-2");
R2.start();
runnable R3 = new runnable(2000000, 2999999, "Thread-3");
R3.start();
//Sum of results from all threads:
System.out.println(runnable.arr);
int totalSum = 0;
for (double i : runnable.arr) {
totalSum += i;
}
long endTime_par = System.currentTimeMillis();
System.out.println("Parallel sum took "+(endTime_par-beginTime_par)+" ms. Sum is "+totalSum);
}
}
Here is the runnable class:
import java.util.ArrayList;
class runnable implements Runnable {
private Thread t;
private int begin;
private int end;
private String threadName;
public runnable(int b, int e, String T_name) {
begin = b;
end = e;
threadName = T_name;
}
static ArrayList<Double> arr = new ArrayList<Double>();
public void run() {
double sum =0;
for (int i = begin; i <= end; i++) {
sum += i;
}
arr.add(sum);
}
public void start() {
if (t == null) {
t = new Thread(this, threadName);
t.start();
}
}
}