java多线程实现0到100相加
时间: 2023-09-10 14:15:08 浏览: 68
好的,以下是Java多线程实现0到100相加的示例代码:
```java
public class SumThread extends Thread {
private int start;
private int end;
private int sum;
public SumThread(int start, int end) {
this.start = start;
this.end = end;
}
public void run() {
for (int i = start; i <= end; i++) {
sum += i;
}
}
public static void main(String[] args) throws InterruptedException {
int n = 100;
int threadCount = 5;
int step = n / threadCount;
SumThread[] threads = new SumThread[threadCount];
for (int i = 0; i < threadCount; i++) {
threads[i] = new SumThread(i * step + 1, i * step + step);
threads[i].start();
}
int sum = 0;
for (int i = 0; i < threadCount; i++) {
threads[i].join();
sum += threads[i].sum;
}
System.out.println("0到" + n + "的和为:" + sum);
}
}
```
以上代码中,我们使用了继承 Thread 类的方式来创建多线程,并将任务拆分成多个子任务分别计算,最后将所有子任务的结果相加得到最终结果。在主线程中,我们使用 join() 方法等待所有子线程完成,然后将它们的结果相加。注意,我们需要将任务拆分成多个子任务,并在子任务中计算结果,以充分利用多线程的优势。
总体上来说,这是一个简单的示例,实际中需要根据具体情况进行适当的修改和优化。