You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中如何避免类构造函数阻塞其他线程?

问题根源与解决方案

你的核心问题在于类的实例化操作是在主线程中同步执行的,而非你期望的子线程内。

为什么会出现当前输出?

当你编写Thread(target=A().method_a)时,Python会先执行A()完成实例化——这会调用A.__init__(睡眠10秒),待这个过程完全结束后,才会把实例的method_a方法作为参数传给Thread。同理B()的实例化也是在主线程中执行的,所以主线程会先等待A.__init__执行完毕,再执行B.__init__,之后才启动两个子线程分别运行method_a和method_b,这就导致了当前的输出顺序。

修正方案

要让实例化和方法调用都在子线程内执行,有两种常用方式:

方式1:封装成独立函数(推荐,可读性更强)

from threading import Thread
from time import sleep

class A:
    def __init__(self):
        sleep(10)
        print('class A __init__ awake')

    def method_a(self):
        sleep(10)
        print('method_a awake')

class B:
    def __init__(self):
        sleep(1)
        print('class B __init__ awake')

    def method_b(self):
        sleep(5)
        print('method_b awake')

# 将实例化和方法调用封装到函数中
def run_a():
    a_instance = A()
    a_instance.method_a()

def run_b():
    b_instance = B()
    b_instance.method_b()

thread_a = Thread(target=run_a)
thread_b = Thread(target=run_b)
thread_a.start()
thread_b.start()

方式2:使用lambda表达式(简洁写法)

from threading import Thread
from time import sleep

class A:
    def __init__(self):
        sleep(10)
        print('class A __init__ awake')

    def method_a(self):
        sleep(10)
        print('method_a awake')

class B:
    def __init__(self):
        sleep(1)
        print('class B __init__ awake')

    def method_b(self):
        sleep(5)
        print('method_b awake')

# 用lambda把实例化和方法调用包装成一个可执行对象
thread_a = Thread(target=lambda: A().method_a())
thread_b = Thread(target=lambda: B().method_b())
thread_a.start()
thread_b.start()

修正后的输出

两种方式都能得到你预期的输出:

class B __init__ awake
method_b awake
class A __init__ awake
method_a awake

内容的提问来源于stack exchange,提问作者sierra_papa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 05:25:13