from threading import Thread,currentThread
import time
from random import randint
class Download(Thread):
def __init__(self, file):
# 這兒父類的init方法必須調(diào)用妻导,否則當前這個創(chuàng)建的對象中就沒有新的線程
super().__init__()
self.file = file
def run(self):
print(currentThread())
print('開始下載:%s' % self.file)
time.sleep(randint(5, 10))
print('%s下載結(jié)束' % self.file)
if __name__ == '__main__':
# time.time(): 獲取當前時間-時間戳
start_time = time.time()
t1 = Download('最強Z.mp4')
t1.start()
t2 = Download('最強A.mp4')
t2.start()
print('====')
# 獲取當前線程
"""
主線程: MainThread
子線程: Thread-數(shù)字(數(shù)字從1開始泳叠。)
"""
print(currentThread())
# 如果一個任務想要在另外一個子線程中的任務執(zhí)行完成后再執(zhí)行担敌,就在當前任務前用子線程對象調(diào)用join方法
# 所以join也會阻塞線程,阻塞到對應的子線程中任務執(zhí)行完為止
t1.join()
# t2.join()
end_time = time.time()
print('總共消耗時間:%.2f' % (end_time - start_time))
<Download(Thread-1, started 17244)>
開始下載:最強Z.mp4
<Download(Thread-2, started 2480)>
====
<_MainThread(MainThread, started 3396)>
開始下載:最強A.mp4
最強Z.mp4下載結(jié)束
總共消耗時間:6.00
最強A.mp4下載結(jié)束