最简单的多线程实例

一、代码
import threading
import time

def threading_run(n,ts):
print(“Threading %s is running”%n)
time.sleep(ts)

start_time = time.time()
#存放每一实例化的线程
t_objs =[]
for i in range(50):
t =threading.Thread(target = threading_run ,args= (i,2))
t.start()
t_objs.append(t)
#出现join的原因:主线程和子线程执行顺序无关联关系,需要join转一下串行
#join 等待所有线程执行完毕再进行下一步,即将并行事件转化为串行执行
for t_s in t_objs:
t_s.join()

run_time = time.time()-start_time
print(run_time)
二、代码注意点
1.使用threading.Thread调用线程
2.通过join()将主线程和子线程转为串行的关系
3.第一个for循环多个线程不断运行
第二个for循环检测所有子线程结束,结束后,才能继续执行主线程,从而实现统计出子线程执行时间。

发布了55 篇原创文章 · 获赞 4 · 访问量 7632

猜你喜欢

转载自blog.csdn.net/qq_44801116/article/details/100940855