简体   繁体   中英

Threads in Java - Sum of N numbers

I tried to perform sum of N numbers using conventional method and also using threads to see the performance of threads. I see that the conventional method runs faster than the thread based. My plan is to break down the upper limit(N) into ranges then run a thread for each range and finally add the sum calculated from each thread.

stats in milliseconds :

248
500000000500000000
-----same with threads------
498
500000000500000000

Here I see the approach using threads took ~500 milliseconds and conventional method took only ~250 seconds. I wanted to know If I am correctly implementing threads for this problem. Thanks

code :

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

class MyThread implements Runnable {
    private int from , to , sum;

    public MyThread(long from , long to) {
        this.from = from;
        this.to = to;
        sum = 0;
    }

    public void run() {
        for(long i=from;i<=to;i++) {
            sum+=i;
        }
    }

    public long getSum() {
        return this.sum;
    }
}


public class exercise {

    public static void main(String args[]) {

        long startTime = System.currentTimeMillis();

        long sum = 0;
        for(long i=1;i<=1000000000;i++) {
            sum+=i;
        }

        long endTime = System.currentTimeMillis();

        long duration = (endTime - startTime);  //Total execution time in milli seconds

        System.out.println(duration);

        System.out.println(sum);



        System.out.println("-----same with threads------");

        ExecutorService executor = Executors.newFixedThreadPool(5);

        MyThread one = new MyThread(1, 100000);
        MyThread two = new MyThread(100001, 10000000);
        MyThread three = new MyThread(10000001, 1000000000);

        startTime = System.currentTimeMillis();


        executor.execute(one);
        executor.execute(two);
        executor.execute(three);

        executor.shutdown();

        // Wait until all threads are finish
        while (!executor.isTerminated()) {

        }

        endTime = System.currentTimeMillis();

        System.out.println(endTime - startTime);

        long thsum = one.getSum() + two.getSum() + three.getSum();

        System.out.println(thsum);
    }
}

It only makes sense to split the work into multiple threads when each thread is assigned the same amount of work.

In your case, the first thread does almost nothing, the second thread does almost 1% of the work, and the third thread does 99% of the work.

Therefore, you pay the overhead for running multiple threads without benefiting from the parallel execution.

Splitting the work evenly, as follows, should yield better results:

MyThread one = new MyThread(1, 333333333);
MyThread two = new MyThread(333333334, 666666667);
MyThread three = new MyThread(666666668, 1000000000);

The multithread part of your example includes the time for thread creation. Thread creation is an expensive operation and I presume that it is responsible for a large share of the difference between the single thread and multithread approaches.

Your question was if you are correctly implementing the threads. Did you mean implementing the runnable tasks? If so, I wonder why you have distributed the number ranges so unevenly. The task three seems to be far bigger than the others and as a result the performance will be close to a single thread version however you choose to set up the threads.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM