用類的方式創建線程---自創建類
import threading
import time
class MyThread(threading.Thread):#自建MyThread類繼承threading.Thread類
def __init__(self, num): #init方法用來拿參數,拿到實例變量
threading.Thread.__init__(self)
self.num = num #它是實例變量,存在對象t1,t2中
def run(self): #run就是父類的方法的重寫
# 來定義每個線程要運行的函數
print("running on number:%s" % self.num)
time.sleep(3)
if __name__ == '__main__':
t1 = MyThread(1) #實例化一個類的對象----創建一個線程
t2 = MyThread(2)
t1.start() #python在start方法中內部封裝了run方法
t2.start()