使用Thread类实现两个子线程: (3)线程1实现100以内的奇数和 线程2实现100以内的偶数和
时间: 2024-03-01 17:53:58 浏览: 200
通过Thread建立线程
下面是使用Thread类实现两个子线程的示例代码:
```java
public class Main {
public static void main(String[] args) throws InterruptedException {
OddThread oddThread = new OddThread();
EvenThread evenThread = new EvenThread();
oddThread.start();
evenThread.start();
oddThread.join();
evenThread.join();
System.out.println("奇数和:" + oddThread.getSum());
System.out.println("偶数和:" + evenThread.getSum());
}
}
class OddThread extends Thread {
private int sum = 0;
@Override
public void run() {
for (int i = 1; i <= 100; i += 2) {
sum += i;
}
}
public int getSum() {
return sum;
}
}
class EvenThread extends Thread {
private int sum = 0;
@Override
public void run() {
for (int i = 2; i <= 100; i += 2) {
sum += i;
}
}
public int getSum() {
return sum;
}
}
```
在主线程中创建两个子线程OddThread和EvenThread,并启动它们。在两个子线程的run方法中分别计算100以内的奇数和偶数的和,并保存到变量sum中。在主线程中使用join方法等待两个子线程执行完毕,然后分别调用getSum方法获取它们的和。最后输出结果。
阅读全文