from threading import Thread,current_thread
from queue import Queue
import time
class ThreadPool:
def __init__(self,n):
self.queue=Queue()
for i in range(n):#在线程池里面开启n个线程
Thread(target=self.run,args=(self.queue,),daemon=True).start()
def run(self,queue):
while True:
task,args=self.queue.get()
print(current_thread(),task(*args))
self.queue.task_done()
def applay_async(self,task,args=()):
self.queue.put((task,args))
def join(self):
self.queue.join()
def func(*args):
time.sleep(4)
#print(1)
return args
pool=ThreadPool(2)
pool.applay_async(func,(1,2))
pool.applay_async(func,(1,2))
pool.join()