threading模块开启多线程

多线程Python示例
本文展示了一个使用Python的threading模块创建多个线程并控制它们执行顺序的示例。通过定义不同的睡眠时间来模拟不同任务的执行时间。
 1 import threading
 2 from time import ctime,sleep
 3 loops = [4,2]
 4 def loop(nloop,nsec):
 5     print('start loop',nloop,'at:',ctime())
 6     sleep(nsec)
 7     print('loop',nloop,'end at:',ctime())
 8 def main():
 9     print('starting at:',ctime())
10     threads = []
11     nloops = range(len(loops))
12 
13     for i in nloops:
14         t = threading.Thread(target=loop,args=(i,loops[i]))
15         threads.append(t)           #进程准备
16     for i in nloops:        
17         threads[i].start()          #进程开始
18     for i in nloops:               #等待进程结束
19         threads[i].join()           #关闭进程
20     print('all done at ',ctime())
21 
22 if __name__ == '__main__':
23     main()

 

转载于:https://www.cnblogs.com/leescre/p/8076270.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值