網絡編程-線程-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)>]
解釋如下圖:
網絡編程-線程-2、如何查看有多少個線程在運行