#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020-10-27 19:03
# @Author : Nuonuo
# @Site :
# @File : Multithreading_ frame.py
# @Software: PyCharm
from concurrent.futures import ThreadPoolExecutor#线程池
import threading
import time
import random
thread_quantity=int(input('线程数量:'))
renwu=[]
renwu_suliang=1000#任务总数
wancheng_renwu_su=0#完成任务数
run_thread_quantity=0#运行线程
threadLock = threading.Lock()#锁
thread_name=['thread:'+str(i) for i in range(thread_quantity)][::-1]
pool = ThreadPoolExecutor(max_workers=thread_quantity)#定义线程池
def run(tim):
global run_thread_quantity,wancheng_renwu_su
linsi=random.randint(1,9)
time.sleep(linsi)
#======================================================
threadLock.acquire()
thread_name.append(tim)
wancheng_renwu_su += 1
print(tim, '结束', linsi,'完成任务数:',wancheng_renwu_su)
run_thread_quantity-=1
threadLock.release()
if __name__ == '__main__':
kstime=time.time()
while True:
time.sleep(0.1)#刷新频率
threadLock.acquire()
jubu=renwu_suliang-wancheng_renwu_su
print('线程池-空闲线程:',len(thread_name),'运行中线程:',run_thread_quantity,'剩余任务数量:',jubu,'任务总数:',renwu_suliang)
if run_thread_quantity<thread_quantity and wancheng_renwu_su<renwu_suliang and jubu>run_thread_quantity:
run_thread_quantity+=1
future = pool.submit(run,(thread_name.pop()))
elif jubu==0:
print('跳出')
break
threadLock.release()
pool.shutdown()
print(time.time()-kstime)
python-线程池封装
最新推荐文章于 2024-01-24 14:44:20 发布