1. 程式人生 > >python多線程的實現

python多線程的實現

ini list div rgs app 調用 pri import 線程的創建

入門案例

 1 import threading,time
 2 ‘‘‘
 3 #線程的創建有兩種方式,1.直接調用,2.繼承
 4 ‘‘‘
 5 # def run(n):
 6 #     print(test,n)
 7 # #1.直接調用
 8 # t1 = threading.Thread(target=run,args=(1,))
 9 # t2 = threading.Thread(target=run,args=(2,))
10 # t1.start()
11 # t2.start()
12 # #2.繼承
13 # class Mythread(threading.Thread):
14 # def __init__(self,n): 15 # super(Mythread,self).__init__() 16 # self.n = n 17 # def run(self): 18 # print(test,self.n) 19 # t1 = Mythread(1) 20 # t2 = Mythread(2) 21 # t1.start() 22 # t2.start() 23 #統計多個線程耗時,考慮到線程的並發執行,所以每個線程各自指向各自的,主線程執行完後會自動結束,並發執行的時間統計思路就是在線程執行後使用jion()方法,類似於java的wait()
24 def run(n): 25 print(thread-,n)
    #為了更加直觀的看到多線程執行的效果,我們使用sleep方法
26 time.sleep(2) 27 start_time = time.time() 28 t_list = [] 29 for i in range(50): 30 t = threading.Thread(target=run,args=({}.format(str(i)),)) 31 t.start() 32 t_list.append(t) 33 for j in t_list: 34 j.join()
35 end_time = time.time() 36 print(cost time = ,end_time - start_time)

python多線程的實現