如何使用多线程实现一问一答呢?可以使用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()