Python模块之threading

模块作用简介:

Python模块之threading

thread模块基本被废弃了,现在多用threading模块来创建和管理子线程

有两种方式来创建线程:
第一种是: 用class继承Thread类,并重写它的run()方法;
第二种是: 在实例化threading.Thread对象的时候,将线程要执行的任务函数作为参数传入线程。


官方 英文 帮助:https://docs.python.org/3/library/
官方 简体中文 帮助:https://docs.python.org/zh-cn/3/library/



必要操作:

>>> import threading
>>> from threading import Thread


安装:

python 内置函数,无需安装


导入包:

>>> import threading


帮助查看:

>>> help(threading)

或 单独查看某个子方法(函数)

>>> help(threading.Timer)


方法(函数):

name:获取或设置线程的名称。
ident:获取线程的标识符。
is_alive():检查线程是否处于活动状态。
setDaemon(daemonic):将线程设置为守护线程,当主线程退出时,守护线程也会被终止。True:主线程退出,子线程也退出; False:主线程退出,子线程不退出,子线程执行完任务后退出。要设置在start()前才能生效。
start():启动线程。
join(timeout):等待线程执行完成,可选地设置超时时间。
run():线程的执行入口点,在线程启动时被调用。
sleep(secs):线程休眠指定的秒数。


参数



返回值

返回True,否则返回False。



使用示例:

示例1: 第一种是: 用class继承Thread类,并重写它的run()方法;

import threading
# 定义一个线程类,继承自threading.Thread
class MyThread(threading.Thread):
def __init__(self, thread_id, name):
threading.Thread.__init__(self)
self.thread_id = thread_id
self.name = name
# 定义线程运行时要执行的代码
def run(self):
print(f"线程 {self.name} ({self.thread_id}) 开始运行")
# 这里可以放置线程需要执行的代码
print(f"线程 {self.name} ({self.thread_id}) 结束运行")
# 创建线程对象
thread1 = MyThread(1, "Thread-1")
thread2 = MyThread(2, "Thread-2")
# 启动线程
thread1.start()
thread2.start()
# 等待线程完成
thread1.join()
thread2.join()
print("所有线程执行完毕")


示例2:第二种是: 在实例化threading.Thread对象的时候,将线程要执行的任务函数作为参数传入线程。

import threading
# 定义一个目标函数作为线程的执行任务
def my_task(arg1, arg2):
# 执行任务的代码
# 创建线程对象
my_thread = threading.Thread(target=my_task, args=(arg1, arg2))
# 启动线程
my_thread.start()

args 参数,必须用元组包裹
args: 线程执行方法接收的参数,该属性是一个元组,如果只有一个参数也需要在末尾加逗号。








相关文章:
Python安装包下载:https://www.cnblogs.com/wutou/p/17709685.html
Pip 源设置:https://www.cnblogs.com/wutou/p/17531296.html
pip 安装指定版本模块:https://www.cnblogs.com/wutou/p/17716203.html


参考、来源:
https://blog.csdn.net/answer3lin/article/details/86511571
https://download.csdn.net/blog/column/12548822/136100722
https://zhuanlan.zhihu.com/p/684322003 (### 示例1)
https://www.runoob.com/python/python-multithreading.html
https://blog.csdn.net/xiangxi1204/article/details/139182028







posted @   悟透  阅读(84)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
历史上的今天:
2020-12-21 种子服务器tracker地址
2020-12-21 迅雷Thunder所有版本+迅雷无法下载替代工具
点击右上角即可分享
微信分享提示