这一节主要学习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往期推荐
继续阅读与本文标签相同的文章
-
一目了然 | 数据库实例性能调优利器:Performance Insights
2026-05-18栏目: 教程
-
云栖大会 | 阿里云招募各大技术领域开发者讨论学习
2026-05-18栏目: 教程
-
研发效能提升 36 计第三课:束水攻沙,持续加快产品交付速度
2026-05-18栏目: 教程
-
云栖大会 | 阿里云招募各大技术领域开发者
2026-05-18栏目: 教程
-
阿里第一颗芯片问世,平头哥发布AI芯片含光800
2026-05-18栏目: 教程
