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:我要唱歌
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值