在 Python 中,可以使用 threading.Event
来确保方法按顺序执行。以下是实现方案:
import threading
class Foo:
def __init__(self):
self.event1 = threading.Event()
self.event2 = threading.Event()
def first(self, printFirst: 'Callable[[], None]') -> None:
printFirst()
self.event1.set() # 释放 second 执行
def second(self, printSecond: 'Callable[[], None]') -> None:
self.event1.wait() # 等待 first 执行完
printSecond()
self.event2.set() # 释放 third 执行
def third(self, printThird: 'Callable[[], None]') -> None:
self.event2.wait() # 等待 second 执行完
printThird()
解释:
-
使用
threading.Event()
作为同步机制:-
event1
确保second()
在first()
之后执行。 -
event2
确保third()
在second()
之后执行。
-
-
first()
执行后,调用event1.set()
释放second()
。 -
second()
通过event1.wait()
确保first()
先执行,然后执行printSecond()
,再调用event2.set()
释放third()
。 -
third()
通过event2.wait()
确保second()
先执行,然后执行printThird()
。
这样可以保证 first()
-> second()
-> third()
按顺序执行。