Python多线程实例|threading模块

Python多线程实例|threading模块,第1张

Python多线程实例|threading模块

Python多线程实例|threading模块实例

代码
import time
import threading

def task_thread(counter):
    print('线程名称:{} 参数:{} 开始时间:{}'.format(threading.current_thread().name,counter,time.strftime("%Y-%m-%d %H:%M:%S")))
    num = counter
    while num:
        time.sleep(5)
        num -= 1
    print('线程名称:{} 参数:{} 开始时间:{}'.format(threading.current_thread().name, counter,time.strftime("%Y-%m-%d %H:%M:%S")))


if __name__ == '__main__':
    print('主线程开始时间:{}'.format(time.strftime("%Y-%m-%d %H:%M:%S")))

    #初始化3个线程,传递不同的参数
    t1 = threading.Thread(target=task_thread, args=(3,))
    t2 = threading.Thread(target=task_thread, args=(2,))
    t3 = threading.Thread(target=task_thread, args=(1,))
    #开启三个线程
    t1.start()
    t2.start()
    t3.start()
    #等待运行结束
    t1.join()
    t2.join()
    t3.join()

    print('主线程结束时间:{}'.format(time.strftime("%Y-%m-%d %H:%M:%S")))
运行结果
主线程开始时间:2021-11-29 21:24:54
线程名称:Thread-1 参数:3 开始时间:2021-11-29 21:24:54
线程名称:Thread-2 参数:2 开始时间:2021-11-29 21:24:54
线程名称:Thread-3 参数:1 开始时间:2021-11-29 21:24:54
线程名称:Thread-3 参数:1 开始时间:2021-11-29 21:24:59
线程名称:Thread-2 参数:2 开始时间:2021-11-29 21:25:04
线程名称:Thread-1 参数:3 开始时间:2021-11-29 21:25:09
主线程结束时间:2021-11-29 21:25:09
今日美图

 

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5625101.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-15
下一篇 2022-12-15

发表评论

登录后才能评论

评论列表(0条)

保存