用Java设计一个多线程程序,求p=1!+2!+3!+4!+5!+6!+7!+8!+9!+10!,用十个线程分别求1!、2!...10!,在主线程中求这十个阶层的和。
时间: 2023-11-24 15:52:12 浏览: 84
基于JDK1.8 ssm框架开发的仿知乎小程序源码
5星 · 资源好评率100%
以下是Java设计的多线程程序,用于计算p=1!+2!+3!+4!+5!+6!+7!+8!+9!+10!:
```java
public class FactorialThread extends Thread {
private int num;
private BigInteger result;
public FactorialThread(int num) {
this.num = num;
}
public BigInteger getResult() {
return result;
}
@Override
public void run() {
result = factorial(num);
}
private BigInteger factorial(int n) {
BigInteger res = BigInteger.ONE;
for (int i = 2; i <= n; i++) {
res = res.multiply(BigInteger.valueOf(i));
}
return res;
}
}
public class MainThread {
public static void main(String[] args) throws InterruptedException {
FactorialThread[] threads = new FactorialThread[10];
BigInteger sum = BigInteger.ZERO;
// 创建10个线程,分别计算1!到10!
for (int i = 0; i < threads.length; i++) {
threads[i] = new FactorialThread(i + 1);
threads[i].start();
}
// 等待所有线程执行完毕
for (FactorialThread thread : threads) {
thread.join();
sum = sum.add(thread.getResult());
}
System.out.println("1!+2!+3!+...+10! = " + sum);
}
}
```
阅读全文