可以通过继承threading.Thread类的方式来自定义线程类,该类必须复写run方法,将线程运行的目标函数定义在run方法内。
import threading import time class MyThread(threading.Thread): def __init__(self,sec): super(MyThread,self).__init__() self.sec = sec self.tname = self.getName() # 调用Thread父类中的getName()方法获取当前线程的名称 def run(self): print("当前运行的线程为-->%s, at %s" % (self.tname,time.ctime())) time.sleep(self.sec) print("线程--%s--运行结束, at %s" % (self.tname,time.ctime())) if __name__ == '__main__': t1 = MyThread(5) # 传入休眠时间,创建线程 t2 = MyThread(10) t1.start() t2.start() print("Main Thread ending...")
运行结果如下所示:
当前运行的线程为-->Thread-1, at Thu Mar 21 14:13:23 2019 当前运行的线程为-->Thread-2, at Thu Mar 21 14:13:23 2019 Main Thread ending... 线程--Thread-1--运行结束, at Thu Mar 21 14:13:28 2019 线程--Thread-2--运行结束, at Thu Mar 21 14:13:33 2019 ***Repl Closed***