Python Threading 學習筆記 | 2、添加線程

  • 2019 年 11 月 5 日
  • 筆記

這一節主要學習Threading模塊的一些基本操作,如獲取線程數,添加線程等。

首先導入Threading模塊

import threading

獲取已激活的線程數

threading.active_count()

查看所有線程信息

threading.enumerate()

查看現在正在運行的線程

threading.current_thread()

添加線程,threading.Thread()接收參數target代表這個線程要完成的任務,需自行定義

import threading  def thread_jobs():  # 定義要添加的線程  print('已激活的線程數:%s' % threading.active_count())  print('所有線程信息:%s' % threading.enumerate())  print('正在運行的線程:%s' % threading.current_thread())  def main():  thread = threading.Thread(target=thread_jobs, )  # 定義線程  thread.start()  # 開始線程  if __name__ == '__main__':  main()

運行結果:

# python 2_add_thread.py  已激活的線程數:2  所有線程信息:[<_MainThread(MainThread, stopped 16800)>, <Thread(Thread-1, started 20512)>]  正在運行的線程 <Thread(Thread-1, started 20512)>

參考文章:https://morvanzhou.github.io/tutorials/python-basic/threading 代碼項目地址:https://github.com/teamssix/Python-Threading-study-note往期推薦