from threading import Thread
import requests
import re
import time
from random import randint
class DownloadThread2(Thread):
"""下載類"""
def __init__(self, file, time):
super().__init__()
self.file = file
self.time = time
def run(self):
print('開始下載:'+self.file)
# t = randint(5, 10)
time.sleep(self.time)
print('%s下載結(jié)束, 總共耗時(shí):%ds' % (self.file, self.time))
class DownloadImageThread(Thread):
def __init__(self, url):
super().__init__()
self.url = url
def run(self):
# 開始下載
file_name = re.split(r'/', self.url)[-1]
print(file_name)
print('%s開始下載' % file_name)
response = requests.get(self.url)
content = response.content
with open('images/'+file_name, 'bw') as f:
f.write(content)
print('%s下載結(jié)束' % file_name)
def creat_thread():
t1 = DownloadThread2('電影1', 6)
t2 = DownloadThread2('電影2', 4)
t1.start()
t2.start()
# 線程對(duì)象調(diào)用join方法,會(huì)導(dǎo)致join后的代碼會(huì)在線程中的任務(wù)結(jié)束后才執(zhí)行
t1.join()
t2.join()
print('電影下載結(jié)束!')
def main():
# t1 = DownloadImageThread('https://image.haha.mx/2015/12/04/middle/2082175_c5c3cc05eb73e4023149e663475d3ab4_1449192201.gif')
# t1.start()
#
# t2 = DownloadImageThread('http://img4.imgtn.bdimg.com/it/u=534897622,845095650&fm=26&gp=0.jpg')
# t2.start()
t0 = Thread(target=creat_thread)
t0.start()
print('========')
for x in range(100):
time.sleep(1)
print(x)