摘要:
下文讲述Python中自定义一个多线程类的方法分享,如下所示:
实现思路:
1.定义一个类继承threading.Thread
2.在自定义类中构造函数重写run方法
例:
Python3中自定义多线程类的示例分享
#maomao365.com
#自定义多线程类的示例说明
import threading
import time
class MyThread(threading.Thread):
def __init__(self, n):
super(MyThread, self).__init__() # 重构run函数必须要写
self.n = n
def run(self):
print("线程", self.n)
time.sleep(1)
print('1秒',self.n)
time.sleep(1)
print('2秒',self.n)
time.sleep(1)
print('3秒',self.n)
time.sleep(1)
if __name__ == "__main__":
t1 = MyThread("线程1")
t2 = MyThread("线程2")
t1.start()
t2.start()
//输出
线程线程 线程1线程2
1秒1秒 线程1线程2
2秒2秒 线程1线程2
3秒3秒 线程1线程2
python自定义多线程类的示例分享