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

    python多线程如何自定义线程类?

    宋雪维宋雪维2021-01-28 15:38:03原创4613

    python中使用多线程处理程序,会比一步步的处理节约很多时间,而且通过创建并继承Python的Thread类,重写run()方法,通过自定义的线程类来创建线程,本文介绍python多线程Thread类定义和如何自定义线程类的过程。

    一、Thread类定义

    1

    threading.Thread(self, group=None, target=None, name=None,agrs=(),kwargs=None, *, daemon=None)

    参数group是预留的,用于将来扩展;

    参数target是一个可调用对象,在线程启动后执行;

    参数name是线程的名字。默认值为“Thread-N“,N是一个数字;

    参数args和kwargs分别表示调用target时的参数列表和关键字参数。

    二、自定义线程类

    1、创建一个类,并继承Python的Thread类,且重写run()方法实现具体的执行顺序由自己来定义。

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    from  threading  import  Thread

    import  time

      

    #创建一个类,并继承Python的Thread类,且重写run()方法实现具体的执行顺序由自己来定义

    class  MyThread(Thread):

         '''time.sleep代表等待10秒后才执行'''

         def  run( self ):

             time.sleep( 2 )

             print ( "我是线程类..." )

      

             '''下面这一段是从源码Thread类中的run方法复制过来的,当然

             没有也许,因为继承了Thread,就会去父类里面找,我这里只是测试用'''

             try :

                 if  self ._target:

                     self ._target( * self ._args,  * * self ._kwargs)

             finally :

                 # Avoid a refcycle if the thread is running a function with

                 # an argument that has a member that points to the thread.

                 del  self ._target,  self ._args,  self ._kwargs

    2、定义一个函数

    1

    2

    def  Bar():

         print ( "Bar..." )

    3、通过自定义的线程类来创建线程,并且关联函数Bar,最后执行这个线程。

    1

    2

    3

    4

    t1  =  MyThread(target = Bar)

    t1.start()

      

    print ( "守护线程执行结束..." )

    需要注意:

    自定义线程不能指定target,因为,自定义线程里面的任务统一都在run方法里面;

    启动线程统一调用start方法,不要直接调用run方法,因为这样不是使用子线程去执行任务。

    以上就是python多线程自定义线程类的有关介绍,希望能对你有所帮助哦~更多python学习推荐:python教程

    专题推荐:python 多线程
    上一篇:python创建多线程的两种方法 下一篇:python多线程线程锁如何使用

    相关文章推荐

    • python中temp是什么意思?• python如何使用TemporaryFile()方法创建临时文件?• python中如何创建带有文件名的临时文件?• python中shell如何逐行输入?

    全部评论我要评论

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

  • 取消发布评论
  • 

    Python学习网