用Java创建10个线程,第1个线程计算从1加到10,第2个线程计算11加到20,...,第10个线程计算91加到100,最后把10个线程结果相加并输出
时间: 2023-12-23 22:06:21 浏览: 38
好的,以下是 Java 的实现示例:
```java
public class SumThread extends Thread {
private int start;
private int end;
private List<Integer> result;
public SumThread(int start, int end, List<Integer> result) {
this.start = start;
this.end = end;
this.result = result;
}
@Override
public void run() {
int sum = 0;
for (int i = start; i <= end; i++) {
sum += i;
}
synchronized (result) {
result.add(sum);
}
}
public static void main(String[] args) throws InterruptedException {
List<Integer> result = Collections.synchronizedList(new ArrayList<>());
List<Thread> threads = new ArrayList<>();
for (int i = 0; i < 10; i++) {
int start = i * 10 + 1;
int end = (i + 1) * 10;
Thread thread = new SumThread(start, end, result);
thread.start();
threads.add(thread);
}
for (Thread thread : threads) {
thread.join();
}
int total = 0;
for (int sum : result) {
total += sum;
}
System.out.println(total);
}
}
```
这个程序会创建10个线程,每个线程计算一段整数的和,然后将计算结果添加到一个共享的列表中。由于多个线程可能同时修改列表,因此我们使用了 Java 中的线程安全集合 `Collections.synchronizedList()` 来保证线程安全。最后,主线程会等待所有线程完成,然后对列表中的所有结果求和并输出。