参考:《Python核心编程》
threading 模块的Thread 类是主要的执行对象,而且,使用Thread类可以有很多方法来创建线程,这里介绍以下两种方法:
如果是有面向对象接口需求的,第二种方法更加符合。
示例代码:
from threading import Thread
from time import sleep, ctime
loops = [4, 2]
def loop(nloop, nsec):
print("start loop ", nloop, " at ", ctime())
sleep(nsec)
print("nloop ", nloop, " done at ", ctime())
def main():
threads = []
print("starting at: ", ctime())
# create all threads
for i in range(len(loops)):
t = Thread(target=loop, args=(i, loops[i]))
threads.append(t)
# start thread
for i in range(len(loops)):
threads[i].start()
# wait for all threads to finish
for i in range(len(loops)):
threads[i].join()
print("all DONE at: ", ctime())
if __name__ == "__main__":
main()
执行脚本:
$ python myThread.py
starting at: Sat Jan 20 17:22:28 2024
start loop 0 at Sat Jan 20 17:22:28 2024
start loop 1 at Sat Jan 20 17:22:28 2024
nloop 1 done at Sat Jan 20 17:22:30 2024
nloop 0 done at Sat Jan 20 17:22:32 2024
all DONE at: Sat Jan 20 17:22:32 2024
$ python myThread.py
starting at: Sat Jan 20 17:45:16 2024
start loop 0 at Sat Jan 20 17:45:16 2024
start loop 1 at Sat Jan 20 17:45:16 2024
all DONE at: Sat Jan 20 17:45:16 2024
nloop 1 done at Sat Jan 20 17:45:18 2024
nloop 0 done at Sat Jan 20 17:45:20 2024
当创建线程时使用子类要相对更容易阅读,而且如上所述,当你需要一个更加符合面向对象的接口时,
会选择这种方法。下面的示例中将对 Thread 子类化,而不是直接对其实例化。这将使我们在定制线程对象时拥有更多的灵活性,也能够简化线程创建的调用过程。
示例代码:
from threading import Thread
from time import sleep, ctime
loops = [4, 2]
class MyThread(Thread):
def __init__(self, func, args, name=''):
Thread.__init__(self) # 调用基类构造方法
self.func = func
self.args = args
self.name = name
def run(self):
self.func(*self.args)
def loop(nloop, nsec):
print("start loop ", nloop, " at ", ctime())
sleep(nsec)
print("loop ", nloop, "done at ", ctime())
def main():
threads = []
# 创建线程
for i in range(len(loops)):
t = MyThread(func=loop, args=(i,loops[i]), name=loop.__name__)
threads.append(t)
# 启动线程
for i in range(len(loops)):
threads[i].start()
# 等待所有线程执行完毕
for i in range(len(loops)):
threads[i].join()
print("all DONE at ", ctime())
if __name__ == "__main__":
main()
执行脚本:
$ python myThread2.py
start loop 0 at Sat Jan 20 18:49:51 2024
start loop 1 at Sat Jan 20 18:49:51 2024
loop 1 done at Sat Jan 20 18:49:53 2024
loop 0 done at Sat Jan 20 18:49:55 2024
all DONE at Sat Jan 20 18:49:55 2024
补:Thread 对象的属性和方法