1. 编写线程程序,在新线程中完成计算某个整数的阶乘。分别用Thread类和Runnable接口实现。
时间: 2024-03-03 07:49:47 浏览: 67
使用Thread类实现:
```java
public class FactorialThread extends Thread {
private int n;
public FactorialThread(int n) {
this.n = n;
}
@Override
public void run() {
int result = 1;
for (int i = 1; i <= n; i++) {
result *= i;
}
System.out.println(n + "! = " + result);
}
}
```
使用Runnable接口实现:
```java
public class FactorialRunnable implements Runnable {
private int n;
public FactorialRunnable(int n) {
this.n = n;
}
@Override
public void run() {
int result = 1;
for (int i = 1; i <= n; i++) {
result *= i;
}
System.out.println(n + "! = " + result);
}
}
```
使用方法:
```java
public class Main {
public static void main(String[] args) {
// 使用Thread类实现
Thread t1 = new FactorialThread(5);
t1.start();
// 使用Runnable接口实现
FactorialRunnable r = new FactorialRunnable(6);
Thread t2 = new Thread(r);
t2.start();
}
}
```
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![c](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)