编写4个线程,第一个线程从1加到25,第二个线程从26加到50,第三个线程从51加到75,第四个线程从76加到100,最后再把四个线程计算的结果相加。
输入格式:
无
输出格式:
最终结果
输入样例:
输出样例:
5050
代码
java
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
SumOfRange s1 = new SumOfRange(1,25);
SumOfRange s2 = new SumOfRange(26,50);
SumOfRange s3 = new SumOfRange(51,75);
SumOfRange s4 = new SumOfRange(76,100);
s1.start();
s2.start();
s3.start();
s4.start();
try {
s1.join();
s2.join();
s3.join();
s4.join();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println(SumOfRange.sum);
}
}
class SumOfRange extends Thread {
private int start;
private int end;
public static int sum;
public SumOfRange(int start, int end) {
this.start = start;
this.end = end;
}
@Override
public void run() {
for(int i=start;i<=end;i++) {
sum+=i;
}
}
}