python线程的批量创建
上篇文章介绍了python线程的基础知识和创建的方法,现在开始介线程的批量创建的方法。
在python3 中创建线程有两种方式,一种是通过threading.Thread直接创建线程并运行,一种是通过继承threading.Thread 类来创建线程。
1.用thread.Thread 直接在线程中运行函数
import threading
def worker(name):
print("thread %s is runing" % name)
worker = threading.Thread(target = worker,args = ('worker',))
worker.start()
worker.join()
运行结果如下:
2.通过继承thread.Thread 来创建线程
import threading
class MyThread(threading.Thread):
def __init__(self, name):
threading.Thread.__init__(self) #这一步是必须的,不加会报错
self.name = name
def run(self):
for i in range(5):
print("thread %s is runing-----%s" %(self.name,i))
worker1 = MyThread('worker1')
worker2 = MyThread('worker2')
worker1.start()
worker2.start()
worker1.join()
worker2.join()
运行结果如下:
thread worker1 is runing-----0thread worker2 is runing-----0
thread worker1 is runing-----1thread worker2 is runing-----1
thread worker1 is runing-----2thread worker2 is runing-----2
thread worker1 is runing-----3thread worker2 is runing-----3
thread worker1 is runing-----4thread worker2 is runing-----4
转载自:https://blog.csdn.net/qq_34246164/article/details/80952004