Python学习笔记3:多线程的示例一

基于python3.6,使用threading模块实现:

 1 import threading
 2 import time
 3 
 4 def run(n):
 5     print("线程启动,线程号:",n)
 6     time.sleep(2)
 7     
 8 start_time = time.time()
 9 t_objs = []
10 
11 for i in range(10):
12     t = threading.Thread(target=run,args=("thread-%s" %i,))
13     t.setDaemon(True) #以守护线程方式启动,主线程程结束会强制结束守护线程。没有这句或False以子线程方式启动,主线程结束前会等待所有子线程结束。
14     t.start()
15     t_objs.append(t) #先不join,先存到列表
16    
17  
18 # for t in t_objs:
19 #     t.join()  #线程阻塞,只有当线程运行结束后才会继续执行后续语句
20 
21 print ("------ 所有线程结束   .....",threading.current_thread())
22 print("cost:",time.time() - start_time)

猜你喜欢

转载自www.cnblogs.com/Pydev/p/9462619.html