多线程-threading
1.多线程
import threadingimport timedef say(): print("Hello!How are you?") time.sleep(1)if __name__=='__main__': for i in range(5): t=threading.Thread(target=say) t.start() #启动线程,即让线程开始执行
- 使用了多线程并发的操作,花费时间要短很多
- 创建好的线程,需要调用
start()
方法来启动
2.主线程等待所有子线程结束或后结束
#coding=utf-8import threadingfrom time import sleep,ctimedef 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())
3.查看线程数
#coding=utf-8import threadingfrom time import sleep,ctimedef 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() while True: length = len(threading.enumerate()) print('当前运行的线程数为:%d' % length) if length <= 1: break sleep(0.5)