搜索
您的当前位置:首页正文

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

来源:二三四教育网

说明

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

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

实例

"""
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学习指路:

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

Top