下面为一个有趣的例子
import threading class Boy(threading.Thread): def __init__(self, cond, name): super(Boy, self).__init__() self.cond = cond self.name = name def run(self): self.cond.acquire() print(self.name + ": 嫁给我吧!?") self.cond.notify() # 唤醒一个挂起的线程,让hanmeimei表态 self.cond.wait() # 释放内部所占用的琐,同时线程被挂起,直至接收到通知被唤醒或超时,等待hanmeimei回答 print(self.name + ": 我单下跪,送上戒指!") self.cond.notify() self.cond.wait() print(self.name + ": Li太太,你的选择太明治了。") self.cond.release() class Girl(threading.Thread): def __init__(self, cond, name): super(Girl, self).__init__() self.cond = cond self.name = name def run(self): self.cond.acquire() self.cond.wait() # 等待Lilei求婚 print(self.name + ": 没有情调,不够浪漫,不答应") self.cond.notify() self.cond.wait() print(self.name + ": 好吧,答应你了") self.cond.notify() self.cond.release() cond = threading.Condition() boy = Boy(cond, "LiLei") girl = Girl(cond, "HanMeiMei") girl.start() boy.start()
运行结果如下:
LiLei: 嫁给我吧!? HanMeiMei: 没有情调,不够浪漫,不答应 LiLei: 我单下跪,送上戒指! HanMeiMei: 好吧,答应你了 LiLei: Li太太,你的选择太明治了。
以上就是python如何切换线程的详细内容,更多请关注php中文网其它相关文章!
声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。
上一篇:python安装哪个版本
下一篇:python如何编写安卓程序