文件一:
import threading
import time
class MyThread(threading.Thread):
def __init__(self, arg):
# 显式的调用父类的初始化函数。
super(MyThread, self).__init__()
self.arg = arg
# 定义每个线程要运行的函数
def run(self):
for i in range(5):
print("test{}:{}".format(self.arg, i+1))
time.sleep(1)
if __name__ == "__main__":
t = MyThread('A')
t.run()
文件二:
from test import MyThread
import time
def test():
i = 0
for i in range(5):
i += 1
print("testB:{}".format(i))
time.sleep(1)
thread_1 = MyThread('A')
thread_1.start()
thread_2 = test()
运行结果:
D:Python3.8.6python.exe D:/PythonWorkSpace/chenbang/test_2.py testA:1 testB:1 testB:2 testA:2 testB:3 testA:3 testB:4 testA:4 testB:5 testA:5 Process finished with exit code 0
应用场景:
当函数封装的越来越多时,通常会把函数分开存放方便管理,这个时候要实现多线程并发运行直接用threading方法就不行了,需要重写run()方法来实现。把自己的函数内容复制到run()下面即可。
注意事项:
实例方法在使用类属性时要加self.
eg:
实例方法run()里要使用类属性arg时,就要在前面加self.



