python 线程、多线程--线程池

使用线程池来管理线程

首先,导入库

from concurrent.futures import ThreadPoolExecutor
import time

其次,在线程池中开启线程

with ThreadPoolExecutor(1) as executor2:  # 开启1个线程,需要跟括号的1对应
    executor2.submit(sayhello, "AA")#线程调用sayhello的方法,传参数AA

def sayhello(a):
    print("hello: " + a)
    time.sleep(2)
    print("hello: b" )

使用示例:

from concurrent.futures import ThreadPoolExecutor
import time


# ************线程池****************
def sayhello(a):
    print("hello: " + a)
    time.sleep(2)


def main():
    seed = ["a", "b", "c"]

    # start2 = time.time()
    # with ThreadPoolExecutor(3) as executor:  # 开启3个线程
    #     for each in seed:
    #         executor.submit(sayhello, each)
    # end2 = time.time()
    # print("时间间隔time2为:" + str(end2 - start2))

    with ThreadPoolExecutor(3) as executor:  # 开启3个线程
        for each in seed:
            executor.submit(sayhello, each)

    start3 = time.time()
    with ThreadPoolExecutor(3) as executor1:  # 开启3个线程
        executor1.map(sayhello, seed)
    end3 = time.time()
    print("时间间隔time3为:time3:" + str(end3 - start3))


    # **********  WY    ************
    with ThreadPoolExecutor(3) as executor2:  # 开启3个线程
        executor2.submit(sayhello, "AA")
        executor2.submit(sayhello, "BB")
        executor2.submit(sayhello, "CC")

if __name__ == '__main__':
    main()

你可能感兴趣的:(python)