美文网首页
day_017 多线程

day_017 多线程

作者: HavenYoung | 来源:发表于2018-08-08 16:55 被阅读0次

    一、多线程1

    • python内置的threading模块,可以支持多线程
    • 所有的进程默认都有一个线程(一般叫这个线程为主线程),其他的线程叫子线程
    • 如果想要在进程中添加其他的线程,就创建线程对象
    import threading
    import time
    
    
    def download(file):
        print('开始下载', file)
        time.sleep(5)
        print(file, '下载结束')
    
    
    if __name__ == '__main__':
        print('='*20)
    
        # 1.创建线程对象
        """
        target:需要在子线程中执行的函数
        args:调用函数的实参列表(参数列表额类型是列表)
        返回值:线程对象
        """
        item1 = ['爱情公寓']
        t1 = threading.Thread(target=download, args=item1)
        # 2.在子线程中执行任务
        t1.start()
    
        item2 = ['狂暴巨兽']
        t2 = threading.Thread(target=download, args=item2)
        t2.start()
    
        # download('爱情公寓')
        # download('狂暴巨兽')
        print('-'*20)
    
        t3 = threading.Thread(target=input, args=['>>>>'])
        t3.start()
        # value = input('>>>>')
        print('!'*20)
    
    

    二、多线程2

    • 1.写一个类,继承自Thread类
    • 2.重写run方法,在里面来规定需要在子线程中执行的任务
    • 3.实现在子线程中执行的任务对应的功能,如果需要参数,通过类的对象属性来传值
    from threading import Thread
    from requests import request
    import re
    
    
    # 下载数据
    class DownloadThread(Thread):
        """下载类"""
        def __init__(self, file_path):
            super().__init__()
            self.file_path = file_path
    
        def run(self):
            """run方法"""
            """
            1.写在这个方法中的内容就是在子线程中执行的类容
            2.这个方法不要直接调用
            """
            print('开始下载')
            response = request('GET', self.file_path)
            data = response.content
            # 获取文件后缀
            pattern = r'\.\w+$'
            suffix = re.search(pattern, self.file_path).group()
    
            with open('./abc' + suffix, 'wb') as f:
                f.write(data)
            print('下载完成')
    
    
    if __name__ == '__main__':
        print('-'*20)
        t1 = DownloadThread('http://10.7.181.117/shareX/Git.exe')
        # 通过start间接调用run方法,run方法中的任务在子线程中执行
        # t1.start()
        # 直接调用run方法,run方法中的任务在当前线程中执行
        # t2.run()
    
        t2 = DownloadThread('https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1533720058151&di=766b5c97653351e805c85881ecaa57d0&imgtype=0&src=http%3A%2F%2Fx.itunes123.com%2Fuploadfiles%2Fb2ab55461e6dc7a82895c7425fc89017.jpg')
        t2.start()
    
        print('=' * 20)
    
    

    三、多线程应用

    import socket
    from threading import Thread
    
    
    class ConversationThread(Thread):
        """在子线程中处理不同的客户端会话"""
        """
        python中可以在函数参数后面加一个冒号,来对参数的类型进行说明
        """
        def __init__(self, conversation: socket.socket, address):
            super().__init__()
            self.conversation = conversation
            self.address = address
    
        def run(self):
            while True:
                self.conversation.send('hello'.encode())
                print(conversation.recv(1024).decode(encoding='utf-8'))
    
    
    if __name__ == '__main__':
        server = socket.socket()
        server.bind(('10.7.181.51', 8080))
        server.listen(50)
    
        while True:
    
            conversation, address = server.accept()
    
            t = ConversationThread(conversation, address)
            t.start()
    
            # while True:
            #     conversation.send('abc'.encode())
            #     print(conversation.recv(1024).decode(encoding='utf-8'))
    
    

    四、子线程阻塞-join

    from threading import Thread, currentThread
    from random import randint
    import time
    
    
    class Download(Thread):
        def __init__(self, file):
            # 这里的父类__init__方法必须调用,否则当期这个创建的对象中就没有新的线程
            super().__init__()
            self.file = file
    
        def run(self):
            print('开始下载:%s' % self.file)
            print(currentThread())
            time.sleep(randint(5, 10))
            print('%s下载结束' % self.file)
    
    
    if __name__ == '__main__':
        # time.time():获取当前时间-时间戳
        start_time = time.time()
        # 获取当前线程
        """
        主线程:MainThread
        子线程:Thread-数字(数字从1开始)
        """
        print(currentThread())
    
        t1 = Download('小视频.mp4')
        t1.start()
    
        t2 = Download('大视频.mp4')
        t2.start()
    
        # 如果一个任务想要在另外一个子线程的任务执行完成后再执行,就在当前任务前就用子线程对象调用join方法
        # 所以join也会阻塞线程,阻塞到对应额子线程中任务执行完为止
        t1.join()
        t2.join()
        end_time = time.time()
        print('花费时间:%.2f 秒' % (end_time-start_time))
    
    

    相关文章

      网友评论

          本文标题:day_017 多线程

          本文链接:https://www.haomeiwen.com/subject/tzexbftx.html