发布于2019-09-09 15:52 阅读(1344) 评论(0) 点赞(14) 收藏(3)
Python3 线程中常用的两个模块为:
threading(推荐使用)
import threading
from time import sleep,ctime
def sing():
for i in range(3):
print("正在唱歌...%d"%i)
sleep(1)
def dance():
for i in range(3):
print("正在跳舞...%d"%i)
sleep(1)
if __name__ == '__main__':
print('---开始---:%s'%ctime())
t1 = threading.Thread(target=sing)
t2 = threading.Thread(target=dance)
t1.start()
t2.start()
#sleep(5) # 屏蔽此行代码,试试看,程序是否会立马结束?
print('---结束---:%s'%ctime())
"""
输出结果:
---开始---:Sat Aug 24 08:44:21 2019
正在唱歌...0
正在跳舞...0---结束---:Sat Aug 24 08:44:21 2019
正在唱歌...1
正在跳舞...1
正在唱歌...2
正在跳舞...2
"""
说明:主线程会等待所有的子线程结束后才结束
为了让每个线程的封装性更完美,所以使用threading模块时,往往会定义一个新的子类class,只要继承threading.Thread就可以了,然后重写run方法。
import threading
import time
class MyThread(threading.Thread):
def run(self):
for i in range(3):
time.sleep(1)
msg = "I'm "+self.name+' @ '+str(i) #name属性中保存的是当前线程的名字
print(msg)
if __name__ == '__main__':
t = MyThread()
t.start()
"""
输出结果:
I'm Thread-5 @ 0
I'm Thread-5 @ 1
I'm Thread-5 @ 2
"""
from concurrent.futures import ThreadPoolExecutor
import time
import os
def sayhello(a):
for i in range(10):
time.sleep(1)
print("hello: " + a)
def main():
seed = ["a", "b", "c"]
# 最大线程数为3,使用with可以自动关闭线程池,简化操作
with ThreadPoolExecutor(3) as executor:
for each in seed:
# map可以保证输出的顺序, submit输出的顺序是乱的
executor.submit(sayhello, each)
print("主线程结束")
if __name__ == '__main__':
main()
作者:前方一片漆黑
链接:https://www.pythonheidong.com/blog/article/104614/5af6feb99de55d8fbb7e/
来源:python黑洞网
任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任
昵称:
评论内容:(最多支持255个字符)
---无人问津也好,技不如人也罢,你都要试着安静下来,去做自己该做的事,而不是让内心的烦躁、焦虑,坏掉你本来就不多的热情和定力
Copyright © 2018-2021 python黑洞网 All Rights Reserved 版权所有,并保留所有权利。 京ICP备18063182号-1
投诉与举报,广告合作请联系vgs_info@163.com或QQ3083709327
免责声明:网站文章均由用户上传,仅供读者学习交流使用,禁止用做商业用途。若文章涉及色情,反动,侵权等违法信息,请向我们举报,一经核实我们会立即删除!