一个函数
我想使用线程的概念解决这样一个问题,输出结果如下所示:
1~100的和是:5050
.
.
.
.
901~1000的和是:95050
1~1000的总和是:
这样一个形式,我写了这样一个程序,麻烦高手改正一下,有好多错误,谢谢!!
class SumThread extends Thread{
int from,to;
long sum;
SumThread(int from,int to){
this.from=from;
this.to=to;
}
long getSum(){
return Sum;
}
public void run(){
for(int i=from;i <=to;i++)
sum+=i;
}
}
public class Thread10{
public static void main(String [] args){
SumThread st1=new SumThread(1,100);
SumThread st2=new SumThread(101,200);
SumThread st3=new SumThread(201,300);
SumThread st4=new SumThread(301,400);
SumThread st5=new SumThread(401,500);
SumThread st6=new SumThread(501,600);
SumThread st7=new SumThread(601,700);
SumThread st8=new SumThread(701,800);
SumThread st9=new SumThread(801,900);
SumThread st10=new SumThread(901,1000);
}
st1.start();
st2.start();
st3.start();
st4.start();
st5.start();
st6.start();
st7.start();
st8.start();
st9.start();
st10.start();
try{
st1.join();
st2.join();
st3.join();
st4.join();
st5.join();
st6.join();
st7.join();
st8.join();
st9.join();
st10.join();
}catch(InterruptedException ie){ }
for(int i=1;i <=10;i++)
System.out.println(from+ "~ "+to+ "的和是: "+getSum());
long Sum=st1.getSum()+st2.getSum()+st3.getSum()+s4t.getSum()+st5.getSum()+st6.getSum()+st7.getSum()+st8.getSum()+st9.getSum()+st10.getSum();
System.out.println( "1~1000的总和是: "+Sum);
}
------解决方案--------------------○_○!!!
大小写先要注意下,然后
System.out.println(from+ "~ "+to+ "的和是: "+getSum());
这句完全...
------解决方案--------------------干嘛要一个一个地写线程,我看你那10个线程都很有规律呀。循环以下产生线程不是很好么?而且还容易看点
------解决方案--------------------class SumThread extends Thread{
int from,to;
long sum;
SumThread(int from,int to){
this.from=from;
this.to=to;
}
long getSum(){
return sum;
}
public void run(){
for(int i=from;i <=to;i++)
sum+=i;
}
}
public class temp{
public static void main(String [] args){
SumThread st1=new SumThread(1,100);
SumThread st2=new SumThread(101,200);
SumThread st3=new SumThread(201,300);
SumThread st4=new SumThread(301,400);
SumThread st5=new SumThread(401,500);
SumThread st6=new SumThread(501,600);
SumThread st7=new SumThread(601,700);
SumThread st8=new SumThread(701,800);
SumThread st9=new SumThread(801,900);
SumThread st10=new SumThread(901,1000);
st1.start();
st2.start();
st3.start();
st4.start();
st5.start();
st6.start();
st7.start();
st8.start();
st9.start();
st10.start();
try{
st1.join();
st2.join();
st3.join();