• 技术文章 >Python技术 >Python基础教程

    python多线程的执行分析

    小妮浅浅小妮浅浅2021-08-20 09:14:42原创3378

    执行说明

    1、多线程执行是GIL锁的存在,实际执行是单线程。

    2、一次只执行一个线程,切换其他线程执行,其中切换时间非常短,看起来像多线程执行。

    实例

    继承Thread类的方式来创建自定义的线程类,然后再创建线程对象并启动线程。

    from random import randint
    from threading import Thread
    from time import time, sleep
     
    class DownloadTask(Thread):
        def __init__(self, filename):
            super().__init__()
            self._filename = filename
     
        def run(self):
            print('开始下载%s...'% self._filename)
            time_to_download = randint(5,10)
            sleep(time_to_download)
            print('%s下载完成!耗费了%d秒' %(self._filename, time_to_download))
     
    def main():
        start = time()
        t1 = DownloadTask('python入门')
        t2 = DownloadTask('av.avi')
        t1.start()
        t2.start()
        t1.join()
        t2.join()
        end = time()
        print('共耗费了%.2f秒'%(end - start))
     
    if __name__ == '__main__':
        main()

    以上就是python多线程的执行分析,希望对大家有所帮助。更多Python学习指路:python基础教程

    本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。

    专题推荐:python多线程
    品易云
    上一篇:python访问元组的两种方法 下一篇:python中mainloop()方法的使用

    相关文章推荐

    • python coroutine的运行过程• python如何输入数据类型检查• python异常的捕捉和补救• python三种流程控制的语句• python析构函数的常见应用• python析构函数的底层机制• python析构函数的使用注意• python中类对象的介绍• python类属性的概念• python类属性的内存分析• python类方法的使用注意• python静态方法的使用注意点• python访问元组的两种方法

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网