多线程猜数字 随机产生一个1000以内的整数 启动三个线程去自动猜 看哪个线程猜的次数最少 从低到高排序
时间: 2024-04-10 13:27:41 浏览: 92
java多线程读取多个文件的方法
以下是一个多线程猜数字的示例代码,可以实现随机产生一个1000以内的整数,启动三个线程去自动猜,并找出猜的次数最少的线程,并按照猜的次数从低到高排序:
```python
import random
import threading
class GuessThread(threading.Thread):
def __init__(self, name):
threading.Thread.__init__(self)
self.name = name
self.count = 0
def run(self):
target_number = random.randint(1, 1000)
guess_number = random.randint(1, 1000)
while guess_number != target_number:
self.count += 1
guess_number = random.randint(1, 1000)
print(f"{self.name} guessed the number {target_number} in {self.count} tries.")
if __name__ == '__main__':
threads = []
for i in range(3):
thread = GuessThread(f"Thread-{i+1}")
thread.start()
threads.append(thread)
for thread in threads:
thread.join()
sorted_threads = sorted(threads, key=lambda x: x.count)
print("Sorted threads based on number of tries:")
for thread in sorted_threads:
print(f"{thread.name}: {thread.count} tries")
```
这段代码创建了三个线程,每个线程会随机生成一个目标数字和猜测数字,直到猜中为止,并记录猜的次数。最后,根据猜的次数对线程进行排序,并输出排序结果。
请注意,每次运行结果可能会不同,因为每个线程的猜测是随机的。
阅读全文