1)可以使用 concurrent.futures 包里的ThreadPoolExecutor,(使用pool.submit提交任务过后都会返回future对象) 2)重载Thread Process类(重载run方法)(注意调用start只是调用了一个方法而已,调用start是开启线程默认会调用run) 3)使用函数创建多线程
ThreadPoolExecutor
from concurrent.futures import ThreadPoolExecutor,Future
def action(a,b):
print('hello,this is %s thread , %s'%(a,b))
if __name__ == '__main__':
pool=ThreadPoolExecutor(max_workers=10)
for each in range(0,6):
future=pool.submit(action(each,2))
print(type(future))
输出:
hello,this is 0 thread , 2
hello,this is 1 thread , 2
hello,this is 2 thread , 2
hello,this is 3 thread , 2
hello,this is 4 thread , 2
hello,this is 5 thread , 2
重载threading.Thread
class MyThread(threading.Thread):
def __init__(self,name):
super().__init__()
self.name=name
def run(self):
print("this is thread "+self.name)
if __name__ == '__main__':
thread1=MyThread("thread1")
thread2 = MyThread("thread2")
thread1.start()
thread2.start()
thread1.join()
thread2.join()
输出:
this is thread thread1
this is thread thread2