• 技术文章 >Python技术 >Python高级

    python创建多线程的两种方法

    宋雪维宋雪维2021-01-28 15:01:47原创4005

    当我们使用python编程的过程中需要多个输出的任务的话,为了能提高效率,可以使用多线程并行处理,那你知道如果穿件多线程使用吗?本文演示python创建多线程的两种方法:1、继承Thread类,并重写它的run()方法;2、用函数创建多线程。

    方法一:继承Thread类,并重写它的run()方法

    import time
    from threading import Thread
    
    
    class MyThread(Thread):
        def __init__(self, name='Python3'):
            super().__init__()
            self.name = name
    
        def run(self):
            for i in range(2):
                print("Hello", self.name)
                time.sleep(1)

    注意:run()方法相当于第一种方法中的线程函数,可以写自己需要的业务逻辑代码,在start()后将会调用。

    方法二:用函数创建多线程

    在Python3中,Python提供了一个内置模块 threading.Thread,可以很方便地让我们创建多线程。

    实例化threading.Thread对象时,将线程要执行的任务函数作为参数传入线程。

    #-*- coding:utf-8 -*-
    import thread
    import time
    def A(para):
        for i in range(5):
            print para
            time.sleep(0.5)
    
    def B(para):
        for i in range(5):
            print para
            time.sleep(0.2)
    
    if __name__ == '__main__':
        thread.start_new_thread(A, ('我是线程A',))
        thread.start_new_thread(B, ('我是线程B',))
        while 1:
            pass

    以上就是python创建多线程的两种方法,大家选择其中一种方法使用即可。更多python学习推荐:python教程

    专题推荐:python 多线程
    品易云
    上一篇:python中Pywin32库如何使用? 下一篇:python多线程如何自定义线程类?

    相关文章推荐

    • python中temp是什么意思?• python中shell的调用• python如何使用TemporaryFile()方法创建临时文件?• python shell怎样在Windows打开?• python中shell如何逐行输入?

    全部评论我要评论

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

  • 取消发布评论
  • 

    Python学习网