开发者社区> 问答> 正文

Java中的线程-N个数字的总和

我尝试使用常规方法以及线程来执行N个数字的总和,以查看线程的性能。我看到常规方法比基于线程的方法运行更快。我的计划是将上限(N)分解为多个范围,然后为每个范围运行一个线程,最后将每个线程计算出的总和相加。

stats in milliseconds :

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

在这里,我看到使用线程的方法花费了大约500毫秒,而传统方法只花费了大约250秒。我想知道我是否为这个问题正确实现了线程。谢谢

代码:

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);
    }
}

展开
收起
垚tutu 2019-12-04 16:39:06 886 0
1 条回答
写回答
取消 提交回答
  • #include

    仅在为每个线程分配相同的工作量时才将工作拆分为多个线程才有意义。

    在您的情况下,第一个线程几乎不执行任何操作,第二个线程几乎完成了1%的工作,第三个线程完成了99%的工作。

    因此,您将为运行多个线程付出开销,而没有从并行执行中受益。

    如下所示,将工作平均分配可以产生更好的结果:

    MyThread one = new MyThread(1, 333333333);
    MyThread two = new MyThread(333333334, 666666667);
    MyThread three = new MyThread(666666668, 1000000000);
    
    2019-12-04 16:39:25
    赞同 展开评论 打赏
问答分类:
问答标签:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
Spring Cloud Alibaba - 重新定义 Java Cloud-Native 立即下载
The Reactive Cloud Native Arch 立即下载
JAVA开发手册1.5.0 立即下载