Omar Hussein Omar Hussein - 4 years ago 195
Java Question

Multithreading summation

I'm tying to sum a big length array (e.g. 30,000,000) and optimizing the time consumption.

I'm following up the multithreading idea ... i wrote a code for 3000 length array for instance and get divided by 3 different threads and get the sum of each third and use just sequential addition in the last step ..

Unfortunately i have a an error in handling exceptions in the 3 threads.
as it is mentioned down in the console message .

Any help ?

//File Name :

package experiment;

import java.util.Arrays;

public class ThreadClassDemo {
public static void main(String[] args) {

double xarr[] = new double[3000];
Arrays.fill(xarr, 1);

double x=0;
Runnable first1 = new DisplayMessage(x,xarr,0,999);
Thread thread1 = new Thread(first1);

double y=0;
Runnable first2 = new DisplayMessage(y,xarr,1000,1999);
Thread thread2 = new Thread(first2);

double z=0;
Runnable first3 = new DisplayMessage(z,xarr,2000,2999);
Thread thread3 = new Thread(first3);


package experiment;
//File Name :
//Create a thread to implement Runnable
public class DisplayMessage implements Runnable {
public double result = 0;
private double arr[];
private int num1;
private int num2;

public DisplayMessage(double i, double[] xarr, int j, int k) {
result = i;
xarr = arr;
num1 = j;
num2 = k;

* public DisplayMessage(String message) { this.message = message; }
public double getresult(){return result;}
public void run() {

try {
for (int i = num1; i <= num2; i++) {
result += arr[i];
} catch (InterruptedException e) {
System.out.println(" interrupted.");


Console :

Exception in thread "Thread-0" Exception in thread "Thread-2" Exception in thread "Thread-1"

Answer Source

Using Java 8 you can do

long sum = IntStream.of(array).parallel().sum();

This will break up the array so that every CPU on you machine can be used.

Note: if you have only a few thousand numbers to add up you might find that starting a thread takes longer. i.e. You need to be summing a really big array to see an improvement.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download