pyhon多執行緒——5、執行緒同步之condition
阿新 • • 發佈:2018-11-12
如何使用多執行緒實現一問一答呢?可以使用condition中的notify和wait方法實現,看程式碼
import threading import time class XiaoAi(threading.Thread): def __init__(self,cond): super().__init__(name='小愛') self.cond = cond def run(self): with cond: cond.wait() print("{}:在".format(self.name)) cond.notify() cond.wait() print("{}:好啊".format(self.name)) cond.notify() cond.wait() print("{}:君住長江尾".format(self.name)) cond.notify() cond.wait() print("{}:共飲長江水".format(self.name)) cond.notify() cond.wait() print("{}:此恨何時已".format(self.name)) cond.notify() cond.wait() print("{}:定不負相思意".format(self.name)) class Tianmao(threading.Thread): def __init__(self,cond): super().__init__(name="天貓精靈") self.cond = cond def run(self): with cond: print("{}:小愛同學".format(self.name)) cond.notify() cond.wait() print("{}:我們來對詩吧".format(self.name)) cond.notify() cond.wait() print("{}:我住長江頭".format(self.name)) cond.notify() cond.wait() print("{}:日日思君不見君".format(self.name)) cond.notify() cond.wait() print("{}:此水幾時休".format(self.name)) cond.notify() cond.wait() print("{}:只願君心似我心".format(self.name)) cond.notify() if __name__ == "__main__": cond = threading.Condition() thread_Ai = XiaoAi(cond) thread_Tian = Tianmao(cond) thread_Ai.start() thread_Tian.start()