黑马程序员技术交流社区

标题: 多线程运用的一些问题~~~求思路·~~~~~! [打印本页]

作者: 杜弦东.    时间: 2015-7-4 09:30
标题: 多线程运用的一些问题~~~求思路·~~~~~!
描述:创建10个线程,第一个线程从1加到10,第二个线程从11加到20·······第十个线程冲91加到100,最后再把10个线程结果想加。

前面是个步奏的思路好说,吧是个线程写出来,分别运行递归。关键是最后一步,如何把所有线程的结果相加!!??

烦请大神给点思路!谢谢
作者: 孙嘉亮    时间: 2015-7-4 10:22
在每个类中写一个得到run()运行结果的方法。
作者: roybill    时间: 2015-7-4 10:42
//编写10个线程,第一个线程从1加到10...最后把10线程结果相加
//继承Thread类
public class Accumulator extends Thread{
        private int startNum;
        public static int sum;
        //带参构造
        public Accumulator(int startNum){
                this.startNum=startNum;
        }
        //同步
        public static synchronized void add(int num){
                sum+=num;
        }
        //调用run()方法
        public void run(){
                int sum=0;
                for(int x=0;x<10;x++){
                        sum+=startNum+x;
                }
                add(sum);
        }
        //主函数抛出异常
        public static void main(String[] args) throws Exception{
                //创建10个线程
                Thread[] threadList=new Thread[10];
                for(int x=0;x<10;x++){
                        threadList[x]=new Accumulator(10*x+1);
                        //启动线程
                        threadList[x].start();
                }
                for(int x=0;x<10;x++){
                        threadList[x].join();
                }
                System.out.println("sum:"+sum);
        }
}




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2