join

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下载结束, 总共耗时:%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下载结束' % file_name)


def creat_thread():
    t1 = DownloadThread2('电影1', 6)
    t2 = DownloadThread2('电影2', 4)
    t1.start()
    t2.start()
    # 线程对象调用join方法,会导致join后的代码会在线程中的任务结束后才执行
    t1.join()
    t2.join()
    print('电影下载结束!')


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)

你可能感兴趣的:(join)