写一个有两个线程的程序,第一个线程用来计算2-1000之间的偶数之和及个数,第二个线程用来计算1000-2000之间的偶数之和及个数(两个线程一个用Thread的子类,一个用Thread类来做)。
时间: 2024-12-20 12:19:33 浏览: 5
编写一个多线程程序,我们可以使用Java的`Thread`类和`Runnable`接口来分别创建两个线程。这里是一个简单的示例:
```java
public class EvenSumCalculator implements Runnable {
private int start;
private int end;
private long sum = 0;
private int count = 0;
public EvenSumCalculator(int start, int end) {
this.start = start;
this.end = end;
}
@Override
public void run() {
for (int i = start; i <= end; i++) {
if (i % 2 == 0) {
sum += i;
count++;
}
}
}
public long getSum() {
return sum;
}
public int getCount() {
return count;
}
}
class OddSumCalculator extends Thread {
private int start;
private int end;
private long oddSum = 0;
private int oddCount = 0;
public OddSumCalculator(int start, int end) {
this.start = start;
this.end = end;
}
@Override
public void run() {
for (int i = start; i <= end; i++) {
if (i % 2 != 0) {
oddSum += i;
oddCount++;
}
}
}
public long getOddSum() {
return oddSum;
}
public int getOddCount() {
return oddCount;
}
}
public class Main {
public static void main(String[] args) {
// 创建并启动偶数线程
EvenSumCalculator evenCalculator = new EvenSumCalculator(2, 1000);
Thread evenThread = new Thread(evenCalculator);
evenThread.start();
// 创建并启动奇数线程
OddSumCalculator oddCalculator = new OddSumCalculator(1000, 2000);
oddCalculator.start();
// 等待线程结束
try {
evenThread.join();
oddCalculator.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("偶数之和: " + evenCalculator.getSum());
System.out.println("偶数个数: " + evenCalculator.getCount());
System.out.println("奇数之和: " + oddCalculator.getOddSum());
System.out.println("奇数个数: " + oddCalculator.getOddCount());
}
}
```
在这个程序中,`EvenSumCalculator`实现了`Runnable`接口,而`OddSumCalculator`继承了`Thread`类。每个线程在其各自的`run()`方法中计算给定范围内的数字之和与个数。主线程会同时启动这两个线程,并在它们结束后打印结果。
阅读全文