使用Thread类实现两个子线程: (1) 线程1实现100以内的奇数和 (2) 线程2实现100以内的偶数和
时间: 2024-03-01 10:53:31 浏览: 143
好的,以下是使用Thread类实现两个子线程的代码:
```java
public class Main {
public static void main(String[] args) {
// 创建线程1和线程2
Thread thread1 = new Thread(new OddNumberSum());
Thread thread2 = new Thread(new EvenNumberSum());
// 启动线程1和线程2
thread1.start();
thread2.start();
// 等待线程1和线程2结束
try {
thread1.join();
thread2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
// 实现线程1,计算100以内的奇数和
class OddNumberSum implements Runnable {
@Override
public void run() {
int sum = 0;
for (int i = 1; i <= 100; i += 2) {
sum += i;
}
System.out.println("奇数和: " + sum);
}
}
// 实现线程2,计算100以内的偶数和
class EvenNumberSum implements Runnable {
@Override
public void run() {
int sum = 0;
for (int i = 2; i <= 100; i += 2) {
sum += i;
}
System.out.println("偶数和: " + sum);
}
}
```
运行结果如下:
```
奇数和: 2500
偶数和: 2550
```
阅读全文