默認(rèn)情況下,一個(gè)進(jìn)程有且只有一個(gè)線程,這個(gè)線程叫主線程
threading模塊中的Thread類就是線程類,這個(gè)類的對(duì)象就是線程對(duì)象,一個(gè)線程對(duì)象對(duì)應(yīng)一個(gè)子線程。
(需要一個(gè)子線程就創(chuàng)建一個(gè)Thread類的對(duì)象)
def download(file):
print('%s開始下載' % file, datetime.now())
# sleep(時(shí)間) - 程序執(zhí)行到這個(gè)位置等待指定的時(shí)候再接著往后面執(zhí)行
time.sleep(10)
print('%s下載結(jié)束' % file, datetime.now())
def main():
print('程序開始')
# print(datetime.now())
# 1.在主線程中下載三個(gè)電影 (總耗時(shí)30s)
# download('槍王之王.mp4')
# download('開國(guó)大典')
# download('黃金國(guó).mp4')
2.在三個(gè)子線程中同時(shí)下載三個(gè)電影
Thread(target,args) - 創(chuàng)建子線程對(duì)象
說(shuō)明:
target - Function,需要傳一個(gè)函數(shù)(這個(gè)函數(shù)中的內(nèi)容會(huì)在子線程中執(zhí)行)
args - 元祖,target對(duì)應(yīng)的函數(shù)的參數(shù)
當(dāng)通過(guò)創(chuàng)建好的子線程對(duì)象調(diào)用start方法的時(shí)候,會(huì)自動(dòng)在子線程中調(diào)用target對(duì)應(yīng)的函數(shù), 并且將args中值作為實(shí)參
創(chuàng)建線程對(duì)象
t1 = threading.Thread(target=download, args=('槍王之王.mp4',))
t2 = threading.Thread(target=download, args=('開國(guó)大典.mp4',))
t3 = threading.Thread(target=download, args=('黃金國(guó).mp4',))
開始執(zhí)行t1對(duì)應(yīng)的子線程中的任務(wù)(實(shí)質(zhì)就是在子線程中調(diào)用target對(duì)應(yīng)的函數(shù))
t1.start()
t2.start()
t3.start()
print('=============')
if __name__ == '__main__':
main()
可以通過(guò)寫一個(gè)類繼承Thread類,來(lái)創(chuàng)建屬于自己的線程類。
1.聲明類繼承Thread
2.重寫run方法。這個(gè)方法中的任務(wù)就是需要在子線程中執(zhí)行的任務(wù)
3.需要線程對(duì)象的時(shí)候,創(chuàng)建當(dāng)前聲明的類的對(duì)象;然后通過(guò)start方法在子線程中去執(zhí)行run方法中的任務(wù)
class DownloadThread(threading.Thread):
"""下載類"""
def __init__(self, file):
super().__init__()
self.file = file
def run(self):
print('開始下載:'+self.file)
print('run:', threading.current_thread())
time1.sleep(10)
print('%s下載結(jié)束' % self.file)
def main():
# 獲取當(dāng)前線程
print(threading.current_thread())
t1 = DownloadThread('沉默的羔羊.mp4')
t2 = DownloadThread('恐怖游輪.mp4')
# 調(diào)用start的時(shí)候會(huì)自動(dòng)在子線程中調(diào)用run方法
t1.start()
t2.start()
` 注意:如果直接用對(duì)象調(diào)用run方法,run方法中的任務(wù)會(huì)在主線程執(zhí)行`
# t1.run()
if __name__ == '__main__':
main()