java 多线程判断素数
时间: 2023-11-24 17:52:50 浏览: 100
以下是Java多线程判断素数的示例代码:
```java
import java.math.BigInteger;
public class PrimeThread extends Thread {
BigInteger number;
public PrimeThread(BigInteger number) {
this.number = number;
}
public void run() {
if (number.isProbablePrime(100)) {
System.out.println(number + " is prime.");
} else {
System.out.println(number + " is not prime.");
}
}
public static void main(String[] args) {
BigInteger[] numbers = new BigInteger[10];
for (int i = 0; i < numbers.length; i++) {
numbers[i] = new BigInteger(50, new Random());
}
for (int i = 0; i < numbers.length; i++) {
new PrimeThread(numbers[i]).start();
}
}
}
```
代码解释:
1. 创建一个名为PrimeThread的类,继承自Thread类。
2. 在PrimeThread类中定义一个BigInteger类型的变量number,表示要判断的数。
3. 在PrimeThread类的构造函数中,将要判断的数赋值给number变量。
4. 重写Thread类的run()方法,在该方法中判断number是否为素数,并输出结果。
5. 在main()方法中,创建一个长度为10的BigInteger数组numbers,用于存储要判断的数。
6. 使用Java的随机数生成器Random生成50位的随机数,并将其存储到numbers数组中。
7. 遍历numbers数组,为每个数创建一个PrimeThread线程,并启动该线程。
阅读全文
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.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)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.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)