python线程
一、python多线程
import threading #导入threading线程模块
import time
def singe():
while True:
thread_name = threading.current_thread().getName() #获取当前线程名称
print(f"{thread_name}:我要唱歌\n")
time.sleep(2)
def dance():
while True:
thread_name = threading.current_thread().getName() #获取当前线程名称
print(f"{thread_name}:我要跳舞\n")
time.sleep(1)
if __name__ == "__main__":
singe_thread = threading.Thread(target=singe,name="thread_singe") #target指定函数对象名称,name指定线程名称
dance_thread = threading.Thread(target=dance,name="thread_dance")
singe_thread.start() #start方法启动线程
dance_thread.start()
运行结果:
thread_dance:我要跳舞
thread_singe:我要唱歌
thread_dance:我要跳舞
二、python线程池
import threading #导入threading线程模块
from concurrent.futures import ThreadPoolExecutor #导入线程池包concurrent.futures的ThreadPoolExecutor模块
import time
def singe(num): #num形参就是iter迭代的一个元素值
while True:
thread_name = threading.currentThread().getName()
print(f"{thread_name}:我要唱歌\n")
time.sleep(num)
if __name__ == "__main__":
with ThreadPoolExecutor(max_workers=5) as pool: #max_worker指定最多线程池的线程数 with方法可以帮助自动关闭线程
results = pool.map(singe,range(1,6)) #map(func,iter) func函数名,iter一个序列迭代的数据集或序列,每一个元素作为实参传递给函数func
运行结果:
ThreadPoolExecutor-0_3:我要唱歌
ThreadPoolExecutor-0_1:我要唱歌
ThreadPoolExecutor-0_0:我要唱歌
ThreadPoolExecutor-0_4:我要唱歌