我们提供了一个类:
public class Foo {
public void one() { print("one"); }
public void two() { print("two"); }
public void three() { print("three"); }
}
三个不同的线程将会共用一个 Foo 实例。
线程 A 将会调用 one() 方法
线程 B 将会调用 two() 方法
线程 C 将会调用 three() 方法
请设计修改程序,以确保 two() 方法在 one() 方法之后被执行,three() 方法在 two() 方法之后被执行。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/print-in-order
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
Python实现:
from threading import Condition, Thread
condtions = [Condition() for _ in range(3)]
def print_num(num):
c, next = condtions[num], condtions[num+1] if num < 2 else None
with c:
c.wait()
print(num, end='-')
if next:
with next:
next.notify_all()
if __name__ == "__main__":
threads = [Thread(target=print_num, args=(i, )) for i in range(3)]
for t in threads:
t.start()
with condtions[0]: #notify first thread to run.
condtions[0].notify_all()
for t in threads:
t.join()