当前位置: 首页 > 图灵资讯 > 行业资讯> Python如何自定义类继承threading.Thread

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

来源:图灵python
时间: 2024-07-30 10:02:39

说明

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

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

实例

"""
使用Python多线程
"""
importtime
importthreading


classMyThread(threading.Thread):

#def__init__(self):
#super().__init__()

defrun(self):
foriinrange(3):
time.sleep(1)
msg="I'm"+self.name+'@'+str(i)#当前线程的名称保存在name属性中
print(msg)


defmain():
t=MyThread()
t.start()

if__name__='__main__':
main()

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

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