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)+"毫秒");
}
}
为什么不能得到正确结果,求大神指点!!!多线程 加法

解决方案 »

  1.   

    对楼主有点无语,楼主的机器能运行下去???
    MyArray ma=new MyArray(len);
    len: 一千万,也就是10M个MyArray
    然后在MyArray的构造函数里:
    a=new long[len];
    10M个long型,一个long型8个字节,总共是80M
    也就是这一句初始化,需要内存:80M*10M
    在楼主的机器上能运行下去???(还是我算的有问题?)
      

  2.   

    楼主确定没看错?哪里不是正确的了。result不是=result1+result2吗?
      

  3.   

    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)+"毫秒");new Thread(mt1).start();
    new Thread(mt2).start();
    这个只是告诉虚拟机这两个线程启动了,所以直接就到了long end2=System.currentTimeMillis();
    所以此时的时间和start2基本是一样的
    等到你打印的时候发现需要用到start2,那么打印的时候就会等待你的线程执行完毕,然后得到result的值,所以en2-start2=0
      

  4.   

    你应该先了解一下线程与线程之间的执行顺序,你在计算result1+result2的时候两个线程还并没有执行,只是进入了就绪状态等待执行,所以你输出的时候是0,只用等到两个线程都执行完毕之后,才能得出正确的值。