如何在类内部封装多线程逻辑并运行多个对象实例
技术百科
聖光之護
发布时间:2026-01-20
浏览: 次 
本文介绍如何将双线程执行逻辑封装进 python 类中,使每个对象实例自主管理其内部的两个并发线程,避免在主程序中手动创建和管理大量线程对象。
在面向对象编程中,良好的封装性意味着对象应尽可能自治——包括其并发行为。原始写法将 threading.Thread 的创建、启动与等待(join)全部暴露在类外部,不仅破坏了封装,还导致主逻辑臃肿、可维护性差,且难以扩展(例如增加线程数或统一生命周期管理)。
通过将线程管理内聚到类中,我们可以定义清晰的接口:run_threads() 启动本实例的全部工作线程,join_threads() 等待它们完成。这样,每个 MyObject 实例都成为一个“可并发执行的单元”。
以下是优化后的完整实现:
import threading
import time
class MyObject:
def __init__(self, item_id):
self.item_id = item_id
def func_one(self):
print(f"[{self.item_id}] func_one started")
time.sleep(1.5) # 模拟耗时操作
print(f"[{self.item_id}] func_one finished")
def func_two(self):
print(f"[{self.item_id}] func_two started")
time.sleep(1.0)
print(f"[{self.item_id}] func_two finished")
def run_threads(self):
"""启动本实例的两个工作线程"""
self.thread1 = threading.Thread(target=self.func_one, name=f"{self.item_id}-func1")
self.thread2 = threading.Thread(target=self.func_two, name=f"{self.item_id}-func2")
self.thread1.start()
self.thread2.start()
def join_threads(self):
"""阻塞等待本实例所有工作线程结束"""
self.thread1.join()
self.thread2.join()
# 使用示例:创建并并发运行多个实例
obj1 = MyObject("item-01")
obj2 = MyObject("item-02")
# 启动所有实例的内部线程(非阻塞)
obj1.run_threads()
obj2.run_threads()
# 等待全部完成(顺序调用,但各实例内线程仍并行执行)
obj1.join_threads()
obj2.join_threads()
print("All instances completed.")✅ 关键优势:
- 高内聚:线程生命周期与对象绑定,self.thread1/self.thread2 属于实例状态;
- 易复用:新增实例只需 objN = MyObject(...); objN.run_threads(); objN.join_threads();
- 可扩展:如需支持动态线程数,可将 func_one/func_two 抽象为列表或注册函数;
- 便于调试:可通过 threading.current_thread().name 或日志明确归属。
⚠️ 注意事项:
- 避免在 __init__ 中直接启动线程(可能导致对象未完全构造就执行);
- 若需线程安全共享状态,请使用 threading.Lock 或其他同步原语;
- join_threads() 必须在 run_threads() 之后调用,否则会引发 RuntimeError(尝试 join 未启动的线程);
- 如需异步等待或超时控制,可改用 thread.join(timeout=...) 并检查 thread.is_alive()。
这种设计既符合 OOP 原则,又保持了多线程的灵活性,是构建可伸缩并发组件的推荐实践。
# 成为一个
# 多个
# python
# 我们可以
# 只需
# 如需
# 或其他
# 并发
# 对象
# 主程序
# 接口
# 线程
# 异步
# 多线程
# 封装
# 类中
# Thread
# 装进
# 封装性
# 面向对象
# 请使用
# 线程生命周期
# 面向对象编程
相关栏目:
<?muma
$count = M('archives')->where(['typeid'=>$field['id']])->count();
?>
【
AI推广<?muma echo $count; ?>
】
<?muma
$count = M('archives')->where(['typeid'=>$field['id']])->count();
?>
【
SEO优化<?muma echo $count; ?>
】
<?muma
$count = M('archives')->where(['typeid'=>$field['id']])->count();
?>
【
技术百科<?muma echo $count; ?>
】
<?muma
$count = M('archives')->where(['typeid'=>$field['id']])->count();
?>
【
谷歌推广<?muma echo $count; ?>
】
<?muma
$count = M('archives')->where(['typeid'=>$field['id']])->count();
?>
【
百度推广<?muma echo $count; ?>
】
<?muma
$count = M('archives')->where(['typeid'=>$field['id']])->count();
?>
【
网络营销<?muma echo $count; ?>
】
<?muma
$count = M('archives')->where(['typeid'=>$field['id']])->count();
?>
【
案例网站<?muma echo $count; ?>
】
<?muma
$count = M('archives')->where(['typeid'=>$field['id']])->count();
?>
【
精选文章<?muma echo $count; ?>
】
相关推荐
- 如何优化Golang Web性能_Golang H
- windows如何备份注册表_windows导出和
- win11如何清理传递优化文件 Win11为C盘瘦
- 微信里的php文件怎么变mp4_微信接收php转m
- Win10闹钟铃声怎么自定义 Win10闹钟自定义
- 如何在 Go 结构体中正确初始化 map 字段
- Windows电脑如何进入安全模式?(多种按键方法
- Windows资源管理器总是卡顿或重启怎么办?(修
- Python数据挖掘进阶教程_分类回归与聚类案例解
- php内存溢出怎么排查_php内存限制调试与优化方
- Python多进程教程_multiprocessi
- 如何使用Golang实现容器自动化运维_Golan
- 如何在 Go 中比较自定义的数组类型(如 [20]
- 如何在JavaScript中动态拼接PHP的bas
- 如何在Golang中处理二进制数据_Golang
- Win11怎么关闭搜索历史_Win11清除任务栏搜
- 如何使用Golang实现云原生应用弹性伸缩_自动应
- PHP cURL GET请求:正确设置认证与自定义
- c++ stringstream用法详解_c++字
- Win11怎么查看显卡显存_查询Win11显卡详细
- PHP主流架构如何做单元测试_工具与流程【详解】
- c# 在ASP.NET Core中管理和取消后台任
- 如何在 Python 中将 ISO 8601 时间
- Win10怎样卸载DockerDesktop_Wi
- Python对象比较排序规则_集合使用说明【指导】
- Win11如何暂停系统更新 Win11暂停更新最长
- Windows10电脑怎么设置自动连接WiFi_W
- Mac如何解压zip和rar文件?(推荐免费工具)
- Win11怎么用设置清理回收站_Win11设置清理
- Mac如何开启夜览模式_Mac护眼模式设置与定时
- VSC怎样在VSC中调试PHPAPI_接口调试技巧
- Python装饰器复用技巧_通用能力解析【教程】
- 怎么将XML数据可视化 D3.js加载XML
- 一文详解网站被黑客入侵挂马解决办法
- Windows10电脑怎么设置虚拟内存_Win10
- Win10路由器怎么隐藏ssid Win10隐藏w
- Windows驱动无法加载错误解决方法_驱动签名验
- 如何在Golang中处理URL参数_Golang
- C#怎么使用委托和事件 C# delegate与e
- Win10如何备份注册表_Win10注册表备份步骤
- php485能和物联网模块通信吗_php485对接
- Windows怎样关闭锁屏广告_Windows关闭
- Go 中 defer 语句在 goroutine
- Python字符串处理进阶_切片方法解析【指导】
- Win11怎么关闭SmartScreen_禁用Wi
- C++如何解析JSON数据?(nlohmann/j
- 如何使用Golang实现多重错误处理_Golang
- Windows10蓝屏代码DPC_WATCHDOG
- c# 如何用c#实现一个支持优先级的任务队列
- Win10怎样清理C盘爱奇艺缓存_Win10清理爱

QQ客服