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)>, <Thread(Thread-1, started 14704)>, <Thread(Thread-2, started 14980)>]
-----test2-----1线程数量是3

-----test1-----1[<_MainThread(MainThread, started 15900)>, <Thread(Thread-1, started 14704)>, <Thread(Thread-2, started 14980)>]

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

线程数量是3
[<_MainThread(MainThread, started 15900)>, <Thread(Thread-1, started 14704)>, <Thread(Thread-2, started 14980)>]
-----test1-----3
线程数量是2
[<_MainThread(MainThread, started 15900)>, <Thread(Thread-1, started 14704)>]
-----test1-----4
线程数量是2
[<_MainThread(MainThread, started 15900)>, <Thread(Thread-1, started 14704)>]
线程数量是1
[<_MainThread(MainThread, started 15900)>]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值