美文网首页
python多线程

python多线程

作者: 像小象的云 | 来源:发表于2018-10-25 20:55 被阅读0次

    每个程序在运行的时候(进程)系统都会为这个进程创建一个线程,这个线程我们叫主线程。程序员自己创建的线程叫子线程。多个任务在一个线程中是按顺序一个一个执行的(线程的串行)。多个线程的任务同时执行。
    在python中创建子线程的方法有两个:

    方法一,直接创建threading.Thread对象
    import time
    import datetime
    from random import randint
    import threading
    
    
    def download(file):
        print(file,threading.current_thread())
        print(datetime.datetime.now(),'开始下载:%s' % file)
    
        # sleep(时间): 会将当前线程阻塞指定的时间(停指定的时间然后再往后执行)
        # 时间单位:秒
        time1 = randint(5, 10)
        time.sleep(time1)
    
        print(datetime.datetime.now(),'下载%s结束'%file,'总共耗时:%d' % time1)
    
    
    """
    python通过threading标准库来支持多线程
    """
    
    if __name__ == '__main__':
    
        # download('肖生克的救赎')
        # current_thread()获取当前线程
        print(threading.current_thread())
    
        # 1.创建一个线程对象
        """
        Thread(target=, args=)
        target: 需要传一个需要在子线程中执行的函数(类型是function的变量)
        agrs: 在子线程中调用target对应的函数的时候,该传什么参数。类型是元祖
        """
        t1 = threading.Thread(target=download, args=('阿甘正传',))
        t2 = threading.Thread(target=download, args=('肖生克的救赎',))
    
        # 2.让子线程去执行任务
        t1.start()
        t2.start()
    
        print('===========')
    
    方法二、通过创建自己的类,该类继承自threading.Thread,然后重写__init__()与run()
    from threading import Thread,current_thread
    import time
    from datetime import datetime
    
    
    
    # 1.创建线程类
    class DownLoadThread(Thread):
    
        """下载线程类"""
        def __init__(self, file):
            super().__init__()
            self.file = file
    
        def run(self):
            # 注意:如果需要给run方法中传数据,通过当前类的属性来传
            print('%s开始下载:' % self.file, datetime.now())
            time.sleep(5)
            print('%s下载结束:' % self.file, datetime.now())
    
    
    # 2.创建线程对象
    t1 = DownLoadThread('阿甘正传')
    t2 = DownLoadThread('沉默的羔羊')
    # 3.通过start去执行run中的任务
    """
    注意: 如果直接调用run方法,run方法中的任务不会在当前的子线程中执行
    """
    # t1.run()
    t1.start()
    t2.start()
    

    相关文章

      网友评论

          本文标题:python多线程

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