编写基于多线程的素数(是除了自身和1以外,没有其他素数因子的自然数)判定程序。待判定的整数经过键盘录人后存放在一个列表中,创建10个线程从列表中取出整数进行判定,判定的结果存人到另一个列表中,用户可以通过键盘查询判定的结果。
时间: 2023-06-02 14:08:11 浏览: 162
好的,这是一个技术问题,我可以回答。以下是基于多线程的素数判定程序的示例:
```python
import threading
# 判断一个数是否为素数
def is_prime(num):
if num < 2:
return False
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
return False
return True
# 多线程素数判定
class PrimeThread(threading.Thread):
def __init__(self, num_list, result_list):
threading.Thread.__init__(self)
self.num_list = num_list
self.result_list = result_list
def run(self):
while True:
try:
num = self.num_list.pop()
except IndexError:
break
if is_prime(num):
self.result_list.append('{}是素数'.format(num))
else:
self.result_list.append('{}不是素数'.format(num))
if __name__ == '__main__':
num_list = input('请输入待判定整数,以逗号分隔: ').split(',')
num_list = [int(num) for num in num_list]
result_list = []
thread_list = []
for i in range(10):
thread = PrimeThread(num_list, result_list)
thread_list.append(thread)
thread.start()
for thread in thread_list:
thread.join()
query = input('请输入要查询的数字: ')
try:
index = num_list.index(int(query))
print(result_list[index])
except ValueError:
print('列表中没有该数字')
```
注意:此处只实现了简单的多线程素数判定,实际应用中需要考虑更多细节和优化,例如线程池、消息队列等。
阅读全文
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.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)