为了更好地对与线程有关的代码进行封装,可以从Thread类派生一个子类。然后将与线程有关的代码都放到这个类中。Thread类的子类的使用方法与Thread相同。从Thread类继承最简单的方式是在子类的构造方法中通过super()函数调用父类的构造方法,并传入相应的参数值。
下面的例子编写一个从Thread类继承的子类MyThread,并重写了父类的构造方法和run方法。最后通过MyThread类创建并启动了两个线程,并使用join方法等待着两个线程结束后再退出程序
import threading
from time import sleep, ctime
# 从Thread类派生的子类
class MyThread(threading.Thread):
# 重写父类的构造方法,其中func是线程函数,args是传入线程函数的参数,name是线程名
def __init__(self, func, args, name=''):
# 调用父类的构造方法,并传入相应的参数值
super().__init__(target=func, name=name,
args=args)
# 重写父类的run方法
def run(self):
self._target(*self._args)
# 线程函数
def fun(index, sec):
print('开始执行', index, '时间:', ctime())
#