class MyArray{
private long[]a;
private int foot;
public MyArray(int len){
this.foot=0;
if(len<0){
a=new long[1];
}else{
a=new long[len];
}
}
public boolean add(long i){
if(this.foot<this.a.length){
a[foot]=i;
this.foot++;
return true;
}else{
return false;
}
}
public long[] getArray(){
return this.a;
}
public long calcuate(int begin,int end){
long sum=0;
for(int i=begin;i<=end;i++){
sum+=a[i];
}
return sum;
}
}
class MyThread1 extends MyArray implements Runnable{
private long result=0;
private int len=0;
public MyThread1(int len){
super(len);
this.len=len;
}
public void run(){
long sum=super.calcuate(0,len/2);
System.out.println("线程一的计算结果:"+sum);
result=sum;
}
public long getResult(){
return this.result;
}
}
class MyThread2 extends MyArray implements Runnable{
private long result=0;
private int len=0;
public MyThread2(int len){
super(len);
this.len=len;
}
public void run(){
long sum=super.calcuate(1+len/2,len-1);
System.out.println("线程二的计算结果:"+sum);
result=sum;
}
public long getResult(){
return this.result;
}
}
public class ThreadDemo{
public static void main(String args[]){
int len=10000000;
MyArray ma=new MyArray(len);
MyThread1 mt1=new MyThread1(len);
MyThread2 mt2=new MyThread2(len);
for(int i=0;i<len;i++){
long n=(long)(Math.random()*9999999);
ma.add(n);
mt1.add(n);
mt2.add(n);
}
long start1=System.currentTimeMillis();
long result1=ma.calcuate(0,len-1);
long end1=System.currentTimeMillis();
System.out.println("计算结果为"+result1+",花费了"+(end1-start1)+"毫秒");
long start2=System.currentTimeMillis();
new Thread(mt1).start();
new Thread(mt2).start();
long result2=mt1.getResult()+mt2.getResult();
long end2=System.currentTimeMillis();
System.out.println("采用双线程计算结果为"+result2+",花费了"+(end2-start2)+"毫秒");
}
}为什么采用双线程计算结果为0,花费了0毫秒?
这里花费的时间是指:从调用双线程到最终得到结果所经历时间
跪求大神给出正确代码多线程加法

解决方案 »

  1.   

    启动thread的几行改成这个:
        Thread t1 = new Thread(mt1);
        t1.start();
        Thread t2 = new Thread(mt2);
        t2.start();
        t1.join();
        t2.join();
      

  2.   

    线程运行的时间,应该在run里计算:
        public void run(){
    long start=System.currentTimeMillis();
            long sum=super.calcuate(0,len/2);       
    long end=System.currentTimeMillis();
            System.out.println("线程一的计算结果:"+sum);
    System.out.println("线程一的耗时:"+(end-start));
            result=sum;
        }