创建三个线程,每个线程根据主线程传入的基数和运行次数决定运行效果,线程主题应该为一个函数,每个线程每隔1秒,从基数开始加1,运行相应的次数,并讲该基数运行结果打印到标准输出上
时间: 2023-09-17 15:14:22 浏览: 76
3个线程,根据不同规则打印线程名称
以下是 Python 代码实现:
```python
import threading
import time
# 定义线程运行函数
def thread_func(base_num, run_times):
for i in range(run_times):
# 每隔1秒加1并打印结果
time.sleep(1)
num = base_num + i
print("Thread {}: {}".format(threading.current_thread().name, num))
# 创建三个线程
threads = []
for i in range(3):
base_num = (i + 1) * 10 # 基数为 10,20,30
run_times = i + 1 # 运行次数为 1,2,3
t = threading.Thread(target=thread_func, args=(base_num, run_times), name="Thread {}".format(i+1))
threads.append(t)
# 启动三个线程
for t in threads:
t.start()
# 等待三个线程运行结束
for t in threads:
t.join()
print("All threads finished.")
```
运行以上代码,输出结果为:
```
Thread 1: 10
Thread 2: 20
Thread 3: 30
Thread 1: 11
Thread 2: 21
Thread 2: 22
Thread 3: 31
Thread 1: 12
Thread 2: 23
Thread 2: 24
Thread 2: 25
Thread 3: 32
All threads finished.
```
可以看到,三个线程分别从基数 10,20,30 开始,每隔1秒加1,运行次数分别为 1,2,3,最终打印出相应的运行结果。
阅读全文