要求从1到100000000累加计算?怎么用多线程实现,要求性能?

解决方案 »

  1.   

    多线程提高性能?这个有点误区,多线程只是让主线程能有空余时间去处理别的事情,但是多线程本身的求和处理就未必如单线程性能高可以考虑把数据分割,每个线程处理一部分数据,最后把个线程的处理结果合并for examplepubic class Test {
        long sum = 0;  //最终总和
        int count = 1; //线程数
        int total = 0; //要累加的数据
        public Test(int count, int total) {
            this.count = count; 
            this.total = total;
        }    public void start() {
            int n = count;
            int avg = total / n; //把数据分割成n个部分
            int from = 0, to = 0;
            for (int i=0; i<n; i++) {
                from = (to == 0 ? i * avg + 1 : to);
                to = (i==n-1 ? total+1 : from + avg);
                new TestThread(from, to).start(); //每个线程处理一部分数据
            }
            while (count > 0) { //等待所有线程执行完成
                Thread.yield();
            }
            System.out.printf("multi-thread: sum=%d\n", sum); //打印结果
        }    public synchronized void update(long value) { //更新最终总和
            this.sum += value;
            this.count--; 
        }    class TestThread extends Thread { //线程
            int from, to;
            public TestThread(int from, int to) {
                this.from = from;
                this.to = to;
            }
            
            public void run() {
                long s = 0;
                for (int i=from; i<to; i++) { //线程处理一部分数据
                    s += i;
                }
                Test.this.update(s); //更新最终总合
            }
        }    public static void main(String[] args) {
            int n = 15, total = 100000000;
            new Test(n, total).start();
            long sum = 0;
            for (int i=0; i<total; i++) {
                sum += (i+1);
            }
            System.out.printf("single-thread: sum=%d\n", sum);
        }
    }
      

  2.   

    三楼这一句Test.this.update(s);是怎么用的啊?不懂ing