本代码演示使用多线程调用继承Thread类和不继承Thread类的实例化对象的方法
代码如下:
from threading import Thread #导入threading库的Thread函数import time #导入时间库class Mythread(Thread): #定义Mythread类,是继承Thread线程 def run(self): #定义run方法 for i in range(4): #遍历4个整数的数组 print("我的线程名是{}____{}".format(self.name,i)) #打印线程名和序号 time.sleep(1) #时间休眠1秒class Mythread2: #定义类Mythread2 def run(num): #定义run方法,参数是num for i in range(num): #遍历num个整数的数组 print(i) #打印i time.sleep(0.5) #时间休眠0.5秒if __name__ == '__main__': t1=Mythread() #创建Mythread类的实例化队形t1,因为Mythread是继承Thread,故不需要用t2这种方式定义线程任务 t1.start() #开始运行t1线程 t2=Thread(target=Mythread2.run,args=(10,)) #定义线程t2,t2的任务是Mythread2类的run方法,参数是10 t2.start() #开始运行t2线程
代码运行结果如下:
我的线程名是Thread-1____0
0
1
我的线程名是Thread-1____1
2
3
4
我的线程名是Thread-1____2
5
6我的线程名是Thread-1____3
7
8
9
图片示例如下:
![bc725dcdd9e5c20d66fa9746eb535a1f.png](https://i-blog.csdnimg.cn/blog_migrate/df3cdd6f1554a0c498ea6dea5957a629.jpeg)