標籤:size 返回 inf png 運行 range image color ...
以上一節代碼為例,如何查看啟動並執行線程數,需要調用threading模組裡面的enumerate方法,返回一個線程數列表:
import threadingimport 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、如何查看有多少個線程在運行