Python 类中的方法如何实现多线程调用?
这么写直接弹框报python运行出错,/尴尬,那这个怎么多线程调用getA/getB/getC/getD/getE呢?每次传参还要循环个arg2list列表
class ThreadTest():
def __init__(self):
pass
def getA(self, args1, args2):
pass
def getB(self, args1, args2):
pass
def getC(self, args1, args2):
pass
def getD(self, args1, args2):
pass
def getE(self, args2):
pass
if name == “main”:
Test = ThreadTest()
args2list = [‘table1’,‘table2’]
args1 = 2
thread_ = []
for args2 in args2list:
t1 = threading.Thread(target=Test.getA, args = (args1, args2))
t2 = threading.Thread(target=Test.getB, args = (args1, args2))
t3 = threading.Thread(target=Test.getE, args = (args2))
t4 = threading.Thread(target=Test.getC, args = (args1, args2))
t5 = threading.Thread(target=Test.getrace, args = (args1, args2))
thread_.append(t1)
thread_.append(t2)
thread_.append(t3)
thread_.append(t4)
thread_.append(t5)
print(thread_)
for t in thread_:
t.setDaemon(True)
t.start()
t.join()
Python 类中的方法如何实现多线程调用?
pool.map ?
在Python类里搞多线程,直接用threading模块就行。比如你想让类里的某个方法在后台跑,可以这样写:
import threading
import time
class MyClass:
def __init__(self):
self.thread = None
self.running = False
def background_task(self):
"""要在后台运行的方法"""
count = 0
while self.running:
print(f"后台任务运行中... {count}")
count += 1
time.sleep(1)
def start_background_task(self):
"""启动后台任务"""
if self.thread and self.thread.is_alive():
print("任务已经在运行了")
return
self.running = True
self.thread = threading.Thread(target=self._run_background_task)
self.thread.start()
print("后台任务已启动")
def _run_background_task(self):
"""包装方法,处理异常"""
try:
self.background_task()
except Exception as e:
print(f"后台任务出错: {e}")
finally:
self.running = False
def stop_background_task(self):
"""停止后台任务"""
self.running = False
if self.thread:
self.thread.join(timeout=2)
print("后台任务已停止")
# 使用示例
if __name__ == "__main__":
obj = MyClass()
obj.start_background_task()
# 主线程继续做其他事情
for i in range(3):
print(f"主线程工作... {i}")
time.sleep(1)
obj.stop_background_task()
这里的关键点:
- 用
threading.Thread创建线程,target参数指向要运行的方法 - 通过
running标志位控制线程的启停 start()方法启动线程,join()方法等待线程结束- 记得处理异常,避免线程静默失败
如果你用的是Python 3.7+,也可以考虑用concurrent.futures,写起来更简洁:
from concurrent.futures import ThreadPoolExecutor
class MyClass:
def process_data(self, data):
return data * 2
def process_multiple(self, data_list):
with ThreadPoolExecutor() as executor:
results = list(executor.map(self.process_data, data_list))
return results
简单说就是根据需求选threading直接控制线程,或者用concurrent.futures做高级封装。
哪尼?

我测试了一下,这样是挨个执行啊,没有并行执行啊,这是单线程吧


把 t.join()注释后也许是你想要的效果。join 的作用是保证当前线程执行完成后,再执行其它线程。
回复图片直接贴网址就行
要把 t.setDaemon(True)也注释掉或者传为 False 才行,但感觉这不是一个完整的多线程了
分开确实可以。。。另外,我帖的只是些伪代码,实际当中还操作了数据库,主要报错原因是多线程查询 数据库报错,还没搞定,心塞_mysql_exceptions.OperationalError: (2013, ‘Lost connection to MySQL server during query’)


