python 获取当前运行线程名称和数量 threading.enumerate()
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)>]
更多推荐
已为社区贡献19条内容
所有评论(0)