Python學習筆記3:多線程的示例一
阿新 • • 發佈:2018-08-12
set range int lse color cos star als read
基於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)
Python學習筆記3:多線程的示例一