• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

Python多线程:主线程等待所有子线程结束代码

python 搞代码 4年前 (2022-01-07) 26次浏览 已收录 0个评论

这篇文章主要介绍了Python多线程:主线程等待所有子线程结束代码,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧

我就废话不多说了,还是直接看代码吧!

 from time import ctime import threading import time def a():     #for i <p style="color:transparent">来源gao!%daima.com搞$代*!码$网</p>in range(5):         print('Program a is running... at ', ctime(),u'.线程名为:',threading.current_thread().name )         time.sleep(0.2)          def b(x):     #for i in range(5):         print('Program b('+x+') is running... at ', ctime(),u'.线程名为:',threading.current_thread().name )         time.sleep(0.1)          if __name__ == '__main__':     print('Mainthread %s is running...' % threading.current_thread().name)     thread_list = []     for i in range(400):#同时运行多个        t1= threading.Thread(target=a)        thread_list.append(t1)             t2 = threading.Thread(target=b, args=('Python',))     thread_list.append(t2)     t3 = threading.Thread(target=b, args=('Java',))     thread_list.append(t3)          for t in thread_list:         t.setDaemon(True)  # 设置为守护线程,不会因主线程结束而中断         t.start()     for t in thread_list:         t.join()  # 子线程全部加入,主线程等所有子线程运行完毕     print('Mainthread %s ended.' % threading.current_thread().name) 

补充知识:Python主线程结束为什么守护线程还在运行?

在实际的交互模式中,主线程只有在Python退出时才终止,所以action函数输出结果还是被打印出来了。”

按照我的理解应该是说,在shell里主线程在输出结果之后并没有真的结束,所以action还会打印结果。

建议把程序编译出来,放到另外的环境中测试,估计就会是你要的结果了。

以上这篇Python多线程:主线程等待所有子线程结束代码就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持gaodaima搞代码网

以上就是Python多线程:主线程等待所有子线程结束代码的详细内容,更多请关注gaodaima搞代码网其它相关文章!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:Python多线程:主线程等待所有子线程结束代码

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址