1 ''' 2 創建線程,也可以動態確定線程數 3 ''' 4 # encoding: utf-8 5 6 7 import threading 8 import time 9 import random 10 11 12 def print_time(thread_name, step): 13 # python的time.ctime()函數把一個時間戳(按秒計算的浮點數)轉化為time.asctime()的形式。 14 # 如果參數未給或者為None的時候,將會默認time.time()為參數。它的作用相當於asctime(localtime(secs))。 15 print(thread_name, ':', time.ctime(time.time())) 16 time.sleep(step) 17 18 19 class MyThread(threading.Thread): 20 # 子類的構造函數必須先調用其父類的構造函數,重寫run()方法。 21 def __init__(self, thid=None, thname=None, step=0.1): 22 threading.Thread.__init__(self) 23 self.step = step 24 self.thid = thid 25 self.thname = thname 26 27 def run(self): 28 for i in range(3): 29 print_time(self.thname, self.step) 30 time.sleep(self.step) 31 print('%s結束' % self.thname) 32 33 print('主線程開始!') 34 35 36 threads = [] 37 for i in range(10): 38 # 創建出來的線程后面還需要使用,所以使用變量th保存起來,保存到循環之前事先創建好的列表里 39 th = MyThread(thname='線程%d' % i, step=round(random.uniform(0, 1), 2)) 40 threads.append(th) 41 th.start() 42 43 for th in threads: 44 th.join() 45 46 print('主線程結束!')