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

631次阅读
没有评论

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

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

一、Thread类定义

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()方法实现具体的执行顺序由自己来定义。

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、定义一个函数

def  Bar():
     print ( "Bar..." )

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

t1  =  MyThread(target = Bar)
t1.start()
 
print ( "守护线程执行结束..." )

需要注意:

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

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

以上就是python多线程自定义线程类的有关介绍,希望能对你有所帮助哦~>。

神龙|纯净稳定代理IP免费测试>>>>>>>>天启|企业级代理IP免费测试>>>>>>>>IPIPGO|全球住宅代理IP免费测试

相关文章:

版权声明:wuyou2021-07-14发表,共计1317字。
新手QQ群:570568346,欢迎进群讨论 Python51学习