栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

python 获取当前运行线程名称和数量 threading.enumerate()

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

python 获取当前运行线程名称和数量 threading.enumerate()

python 获取当前运行线程名称和数量 threading.enumerate()
import threading
import time


def test1():
    for i in range(5):
        print("-----test1-----%s" % i)
        time.sleep(1)


def test2():
    for i in range(3):
        print("-----test2-----%s" % i)
        time.sleep(1)


def main():
    # 在调用thread之前打印当前线程信息
    print(threading.enumerate())
    # 创建线程
    t1 = threading.Thread(target=test1)
    t2 = threading.Thread(target=test2)

    t1.start()
    t2.start()

    # 查看线程列表和数量
    while True:
        # threading.enumerate(): 返回一个包含正在运行的线程的list,包含线程名称和标识id。
        thread_num = len(threading.enumerate())
        print("线程数量是%d" % thread_num)
        print(threading.enumerate())
        if thread_num <= 1:
            break
        time.sleep(1)


if __name__ == '__main__':
    main()
[<_MainThread(MainThread, started 15900)>]
-----test1-----0
-----test2-----0
线程数量是3
[<_MainThread(MainThread, started 15900)>, , ]
-----test2-----1线程数量是3

-----test1-----1[<_MainThread(MainThread, started 15900)>, , ]

线程数量是3
[<_MainThread(MainThread, started 15900)>, , ]
-----test1-----2-----test2-----2

线程数量是3
[<_MainThread(MainThread, started 15900)>, , ]
-----test1-----3
线程数量是2
[<_MainThread(MainThread, started 15900)>, ]
-----test1-----4
线程数量是2
[<_MainThread(MainThread, started 15900)>, ]
线程数量是1
[<_MainThread(MainThread, started 15900)>]
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1022340.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号