Python 备查 线程池

复制粘贴,直接运行。
然后根据需要自己改。

from concurrent.futures import ThreadPoolExecutor
import time
import random

def start():
    '''
    主方法
    '''
    # 待处理列表
    # 将此列表作为参数传递给线程池的执行器,
    # 线程池会根据为列表中的每项单独分配一个线程,
    # 并执行预定义方法。
    lsn = range(100)
    # 线程池中的线程数
    threadCount = 3
    # 使用线程池对列表执行预定义方法
    with ThreadPoolExecutor(threadCount) as e:
        e.map(threadFunction, lsn)
    # 接收预定义方法的返回值
    lre = []
    # 使用线程池对列表执行预定义方法,并将返回结果加入列表
    with ThreadPoolExecutor(threadCount) as e:
        for item in e.map(threadFunction, lsn):
            if item:
                lre.append(item)
    print(lre)

def threadFunction(sn):
    '''
    线程执行方法
    '''
    # 随机休眠
    time.sleep(random.randint(1, 10)/100)
    print(getTimeStamp(), sn)
    return sn

def getTimeStamp():
    # 时间戳 毫秒
    shm = str(int(time.time()*1000))[-3:]
    return time.strftime("%Y%m%d_%H%M%S_", time.localtime()) + shm

if __name__ == "__main__":
    start()
posted @ 2020-07-22 11:35  太晓  阅读(148)  评论(0编辑  收藏  举报