|
|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
代码:
"""
import threading
import math
import os
# 自定义中断类
class mythread(threading.Thread):
# 构造方法
def __init__(self,name):
threading.Thread.__init__(self,name=name)
self.num1=num
# 重写run方法
def run(self):
OutPrime(self.name)
def isprime(k):
# 如果为2或者3时 为质数
if k == 2 or k == 3:
return True
# 不在6的倍数两侧的一定不是质数
if k % 6 != 1 and k % 6 != 5:
return False
# 取num的平方根
tmp = int(math.sqrt(k)) + 1
# 在6的倍数的两侧的也可能不是质数
for i in range(5, tmp, 6):
if k % i == 0 or k % (i + 2) == 0:
return False
# 是质数
return True
def OutPrime(name):
global num
global lock
while num!=0:
lock.acquire() # 得到一个锁,锁定
if isprime(num):
print("线程:", name, "质数:", num)
PrimeList.append(num)
num = num - 1 # 票售完 退出程序
lock.release() # 释放锁
# Start of the main function
num= 1000 # 初始化票数
lock = threading.Lock() # 创建锁
PrimeList=[]
threadlist=[]
for k in range(10):
th=mythread("thread"+str(k))
th.start()
运行结果:……
线程: thread1 质数: 37
线程: thread1 质数: 31
线程: thread1 质数: 29
线程: thread1 质数: 23
线程: thread1 质数: 19
线程: thread1 质数: 17
线程: thread1 质数: 13
线程: thread1 质数: 11
线程: thread1 质数: 7
线程: thread1 质数: 5
线程: thread1 质数: 3
线程: thread1 质数: 2
线程: thread1 质数: 1
Exception in thread thread5:
Traceback (most recent call last):
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36\lib\threading.py", line 916, in _bootstrap_inner
self.run()
File "D:\设计项目\阶乘练习\test.py", line 232, in run
OutPrime(self.name)
File "D:\设计项目\阶乘练习\test.py", line 253, in OutPrime
if isprime(num):
File "D:\设计项目\阶乘练习\test.py", line 241, in isprime
tmp = int(math.sqrt(k)) + 1
ValueError: math domain error
请求帮助,错误提示是什么意思;怎么改?
|
|