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

    Python如何自定义类继承threading.Thread

    小妮浅浅小妮浅浅2021-07-21 09:32:01原创3412

    说明

    1、使用threading模块可以完成多任务的程序开发。

    2、为了使每个线程的封装更加完美,在使用threading模块时,通常会定义一个新的子类class,只需继承threading.Thread即可,然后重写run方法。

    实例

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    23

    24

    25

    """

    Python多线程的使用

    """

    import time

    import threading

      

      

    class MyThread(threading.Thread):

         

        # def __init__(self):

        #    super().__init__()

         

        def run(self):

            for i in range(3):

                time.sleep(1)

                msg = "I'm "+self.name+' @ '+str(i) #name属性中保存的是当前线程的名字

                print(msg)

      

                 

    def main():

        t = MyThread()

        t.start()

         

    if __name__ == '__main__':

    main()

    以上就是Python自定义类继承threading.Thread的方法,希望对大家有所帮助。更多Python学习指路:python基础教程

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

    专题推荐:python
    上一篇:Python threading模块的常用方法 下一篇:Python map接收参数的探究

    相关文章推荐

    • python中figure()函数画两张图• python中subplot函数怎么画图?• python局部作用域是什么• python异常时的语句处理• python中random模块求随机数• python列表如何传递到线程?• Python threading模块的常用方法

    全部评论我要评论

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

  • 取消发布评论
  • 

    Python学习网