题目
利用Runnable接口编写一多线程,计算
1
n
1^{n}
1n +
2
n
2^{n}
2n +
3
n
3^{n}
3n +
m
n
m^{n}
mn ,要求一个线程计算m=4,n=4,一个线程计算m=6,n=3时公式的和,且运行过程中交叉输出所计算的结果。 提示:使用sleep()方法实现多线程。 程序运行时输出的结果: m=6,n=3的和=1 m=4,n=4的和=1 m=6,n=3的和=9 m=4,n=4的和=17
/**
* @Auther: 茶凡
* @ClassName factorial
* @Description TODO
* @date 2023/6/8 15:54
* @Version 1.0
*/
public class Factorial {
public static void main(String[] args) throws InterruptedException {
Factorial factorial = new Factorial();
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
factorialFun(4,4);
}
});
Thread thread1 = new Thread(new Runnable() {
@Override
public void run() {
factorialFun1(6,3);
}
});
thread.start();
thread1.start();
try {
// 让主线程等待子线程执行完毕
thread.join();
thread1.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void factorialFun(int m,int n){
double sum = 0;
int i = 1;
while(m>=i){
sum += Math.pow(i++,n);
System.out.println("m=4,n=4的和 = " + sum);
}
}
public static void factorialFun1(int m,int n){
double sum = 0;
int i = 1;
while(m>=i){
sum += Math.pow(i++,n);
System.out.println("m=6,n=3的和 = " + sum);
}
}
}
测试结果
m=4,n=4的和 = 1.0 m=6,n=3的和 = 1.0 m=4,n=4的和 = 17.0 m=6,n=3的和 = 9.0 m=4,n=4的和 = 98.0 m=6,n=3的和 = 36.0 m=4,n=4的和 = 354.0 m=6,n=3的和 = 100.0 m=6,n=3的和 = 225.0 m=6,n=3的和 = 441.0
|