import threadingimport time# 线程类# 使用一个类来管理线程,但这个类却不继承自 threadig.Thread# 这样的好处是这个类不再依赖于 threading.Thread 模块,而是独立地定义一段可并行运行的代码,可用于 multiprocessing 等模块class ThreadGo:def __init__(self, name="", event=None, *args, **kwargs):self.args = argsself.kwargs = kwargsself.name = nameself.event = eventself.go = True#终止线程def terminate(self):self.go = False#线程函数def run(self, times, txt):while self.go and times > 0:print(txt)times -= 1time.sleep(.5)self.event.set()# 一个线程发出"事件"信号,一个或多个其他线程等待它。event1 = threading.Event()event2 = threading.Event()# 创建线程(使用一个对象方法)tg = ThreadGo(event=event1, times=5, txt="555")th = threading.Thread(target=tg.run, name=tg.name, args=tg.args, kwargs=tg.kwargs)# 启动线程th.start()event1.wait() # 阻塞等待# 创建线程(使用一个对象方法)tg = ThreadGo(event=event2, times=3, txt="333")th = threading.Thread(target=tg.run, name=tg.name, args=tg.args, kwargs=tg.kwargs)# 启动线程th.start()event2.wait() # 阻塞等待print("exit...")
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。