网络编程-线程-2、如何查看有多少个线程在运行

以上一节代码为例,如何查看运行的线程数,需要调用threading模块里面的enumerate方法,返回一个线程数列表:

import threading
import time

"""以上一章的代码为例,如何查看有多少个线程在运行"""


def sing():
    """唱歌5秒钟"""
    for i in range(3):
        print('----------------')
        print('我在唱歌....')
        time.sleep(1)


def dance():
    for i in range(5):
        print('我在跳舞....')
        print('----------------')
        time.sleep(1)


def main():
    t = threading.Thread(target=sing)  
    t2 = threading.Thread(target=dance)
    t.start()
    t2.start()
    # 循环打印正在运行的线程数,调用threading模块中的enumerate方法返回一个列表,里面的元素就是运行的线程,打印出元素个数就是线程数
    while True:
        nums = len(threading.enumerate())
        print(threading.enumerate())
        # 当没有线程时,就退出
        if nums <= 1:
            break
        time.sleep(1)

if __name__ == '__main__':
    main()

运行结果如下:

我在唱歌....
我在跳舞....
[<_MainThread(MainThread, started 26264)>, <Thread(Thread-1, started 23804)>, <Thread(Thread-2, started 24216)>]
[<_MainThread(MainThread, started 26264)>, <Thread(Thread-1, started 23804)>, <Thread(Thread-2, started 24216)>]
我在跳舞....
我在唱歌....
[<_MainThread(MainThread, started 26264)>, <Thread(Thread-1, started 23804)>, <Thread(Thread-2, started 24216)>]
我在唱歌....
我在跳舞....
[<_MainThread(MainThread, started 26264)>, <Thread(Thread-1, started 23804)>, <Thread(Thread-2, started 24216)>]
我在跳舞....
[<_MainThread(MainThread, started 26264)>, <Thread(Thread-2, started 24216)>]
我在跳舞....
[<_MainThread(MainThread, started 26264)>, <Thread(Thread-2, started 24216)>]
[<_MainThread(MainThread, started 26264)>]

 

解释如下图:

 

posted @ 2018-07-22 21:43  上海小盖伦  阅读(808)  评论(0编辑  收藏  举报