import threading, timeclass Hider(threading.Thread):def __init__(self, cond, name):threading.Thread.__init__(self)self.cond = condself.name = namedef run(self):self.cond.acquire() #获取锁print(self.name + ': 我已经把眼睛蒙上了')self.cond.notify() #唤醒其他线程 此方法在调用线程已经获取锁之后调用self.cond.wait() #释放锁-睡眠-获取锁 此方法在调用线程已经获取锁之后调用print(self.name + ': 我找到你了 ~_~')self.cond.notify() #唤醒其他线程self.cond.release() #释放锁print(self.name + ': 我赢了')class Seeker(threading.Thread):def __init__(self, cond, name):threading.Thread.__init__(self)self.cond = condself.name = namedef run(self):self.cond.acquire() #获取锁self.cond.wait() #释放锁-睡眠-获取锁print(self.name + ': 我已经藏好了,你快来找我吧')self.cond.notify() #唤醒其他线程self.cond.wait() #释放锁-睡眠-获取锁self.cond.release() #释放锁print(self.name + ': 被你找到了,哎~~~')cond = threading.Condition()seeker = Seeker(cond, 'seeker')hider = Hider(cond, 'hider')seeker.start()#先运行等待线程,如果先运行 notify() ,那么后面的 wait() 仍然会阻塞while not seeker.is_alive(): passhider.start()
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。