2. 并发计算模拟 计算从1到1亿整型数相加。要求使用并发程序处理,即采用多线程实现,在主线程中将计算结果累加(不能使用累加公式)。 大致思路: (1)编写SumWorker类,实现Runnable接口,计算从m到n的和,其中m,n由构造方法传入; (2)在主程序中每次开启若干个SumWorker线程(具体数量由程序指定或者用户输入),计算完成之后,将部分结果累加,然后再启动另一批线程,直到计算完成。
时间: 2023-06-24 19:04:01 浏览: 82
下面是一个简单的Java代码实现,其中SumWorker类用于计算从m到n的和,主程序则创建多个SumWorker线程来实现并发计算。
```
import java.util.Scanner;
public class ConcurrentSum {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入线程数量:");
int threadCount = scanner.nextInt();
long start = 1;
long end = 100000000;
long sum = 0;
long step = (end - start + 1) / threadCount;
SumWorker[] workers = new SumWorker[threadCount];
for (int i = 0; i < threadCount; i++) {
long m = start + i * step;
long n = m + step - 1;
if (i == threadCount - 1) {
n = end;
}
workers[i] = new SumWorker(m, n);
Thread t = new Thread(workers[i]);
t.start();
}
for (int i = 0; i < threadCount; i++) {
try {
workers[i].join();
sum += workers[i].getResult();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("1到1亿的整数相加的结果为:" + sum);
}
static class SumWorker implements Runnable {
private long m;
private long n;
private long result;
public SumWorker(long m, long n) {
this.m = m;
this.n = n;
}
public long getResult() {
return result;
}
@Override
public void run() {
long sum = 0;
for (long i = m; i <= n; i++) {
sum += i;
}
result = sum;
}
}
}
```
运行程序后,会提示用户输入线程数量,然后会创建指定数量的SumWorker线程来进行并发计算,最后将各个线程计算得到的结果累加起来,得到1到1亿整数相加的结果。
阅读全文