#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@File : thread_test.py
@Time : 2019/06/14 16:13:56
@Author : Ni Dazhong
@Version : 1.0
@Desc : use python3.x
'''
from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor, wait
import os, time, random, logging
logging.basicConfig(
level = logging.DEBUG,
format = '%(asctime)s %(levelname)s %(process)d --- [%(threadName)s] %(filename)s %(funcName)s %(lineno)d : %(message)s',
datefmt = '%Y-%m-%d %H:%M:%S',
)
def run_task(identifier, sleep_time):
logging.info("task %s running ..."%(identifier))
time.sleep(sleep_time) # 模拟方法执行时间
return sleep_time
if __name__ == "__main__":
start_time = time.time()
executor = ThreadPoolExecutor(max_workers=3)
tasks = []
for i in range(5):
random_sleep = random.randint(1,5)
task = executor.submit(run_task, i, random_sleep)
task_info = {}
task_info["identifier"] = i
task_info["random_sleep"] = random_sleep
task_info["task"] = task
tasks.append(task_info)
print(wait([t["task"] for t in tasks], 4)) # wait方法等待4 秒查看线程运行状态
for t in tasks:
print("task{} random_sleep {}s, isDone: {} ".format(t["identifier"], t["random_sleep"], t["task"].done()))
运行结果
$ python thread_test.py
2019-06-14 17:19:13 INFO 52688 --- [ThreadPoolExecutor-0_0] thread_test.py run_task 22 : task 0 running ...
2019-06-14 17:19:13 INFO 52688 --- [ThreadPoolExecutor-0_1] thread_test.py run_task 22 : task 1 running ...
2019-06-14 17:19:13 INFO 52688 --- [ThreadPoolExecutor-0_2] thread_test.py run_task 22 : task 2 running ...
2019-06-14 17:19:14 INFO 52688 --- [ThreadPoolExecutor-0_0] thread_test.py run_task 22 : task 3 running ...
2019-06-14 17:19:16 INFO 52688 --- [ThreadPoolExecutor-0_2] thread_test.py run_task 22 : task 4 running ...
DoneAndNotDoneFutures(done={,
int>}, not_done={, , })
task0 random_sleep 1s, isDone: True
task1 random_sleep 5s, isDone: False
task2 random_sleep 3s, isDone: True
task3 random_sleep 4s, isDone: False
task4 random_sleep 4s, isDone: False
结果分析
代码中指定线程池只有3个可用线程, 可见打印日志也只有ThreadPoolExecutor-0_0/1/2 三个线程, 其中主线程wait 了4买哦