求1~1000的和,现在创建10个线程,利用线程数组组织线程(效率会更高些)
运行结果如下:
1~100的和:5050
101~200的和:15050
201~300的和:25050
...
901~1000的和:95050
总和:500500如下是我写的代码,有点错误,本人是新手,改错能力差,望高手指点,先谢了!
public class Thread{
public static void main(String[] args){
SumThread[] st=new SumThread[10];
for(int i=0;i<10;i++){
st[i]=new SumThread(i*100+1,(i+1)*100);
st[i].start();
try{
st[i].join();
}catch(InterruptedException ie){}
long sum+=st[i].getSum();
System.out.println("1~1000的和:"+sum);
}
}
}
运行结果如下:
1~100的和:5050
101~200的和:15050
201~300的和:25050
...
901~1000的和:95050
总和:500500如下是我写的代码,有点错误,本人是新手,改错能力差,望高手指点,先谢了!
public class Thread{
public static void main(String[] args){
SumThread[] st=new SumThread[10];
for(int i=0;i<10;i++){
st[i]=new SumThread(i*100+1,(i+1)*100);
st[i].start();
try{
st[i].join();
}catch(InterruptedException ie){}
long sum+=st[i].getSum();
System.out.println("1~1000的和:"+sum);
}
}
}
sum需要放在for循环外面,不然,每次都是重新赋值class MyThread
{
public static void main(String[] args)
{
SumThread[] st = new SumThread[10];
long sum = 0;
for (int i = 0; i < 10; i++)
{
st[i] = new SumThread(i * 100 + 1, (i + 1) * 100);
st[i].start();
try
{
st[i].join();
}
catch (InterruptedException ie)
{
}
sum += st[i].getSum();
}
System.out.println("1~1000的和:" + sum);
}} class SumThread extends Thread
{
private int begin;
private int end;
private int sum;
SumThread(int begin, int end)
{
this.begin = begin;
this.end = end;
}
public void run ()
{
sum = (end + begin) * (end - begin+1)/2;
}
public int getSum()
{
return sum;
}
}