首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

Python Threading 学习笔记 | 2、添加线程

这一节主要学习Threading模块的一些基本操作,如获取线程数,添加线程等。

首先导入Threading模块

代码语言:javascript
复制
import threading

获取已激活的线程数

代码语言:javascript
复制
threading.active_count()

查看所有线程信息

代码语言:javascript
复制
threading.enumerate()

查看现在正在运行的线程

代码语言:javascript
复制
threading.current_thread()

添加线程,threading.Thread()接收参数target代表这个线程要完成的任务,需自行定义

代码语言:javascript
复制
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()

运行结果:

代码语言:javascript
复制
# 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往期推荐

下一篇
举报
领券