在Python中,可以使用threading模块来创建和管理线程。在线程中,可以使用Event对象或者Condition对象来实现线程的暂停和恢复。
Event对象来实现线程的暂停和恢复:创建一个Event对象:event = threading.Event()在线程中使用event.wait()来暂停线程,直到收到信号。使用event.set()来发送信号,恢复线程。示例代码:
import threadingimport timedef worker(event): print("Worker thread started") event.wait() # 等待收到信号 print("Worker thread resumed") # 执行其他操作event = threading.Event()t = threading.Thread(target=worker, args=(event,))t.start()time.sleep(2) # 等待2秒event.set() # 发送信号,恢复线程使用Condition对象来实现线程的暂停和恢复:创建一个Condition对象:condition = threading.Condition()在线程中使用condition.wait()来暂停线程,直到收到信号。使用condition.notify()或者condition.notifyAll()来发送信号,恢复线程。示例代码:
import threadingimport timedef worker(condition): print("Worker thread started") with condition: condition.wait() # 等待收到信号 print("Worker thread resumed") # 执行其他操作condition = threading.Condition()t = threading.Thread(target=worker, args=(condition,))t.start()time.sleep(2) # 等待2秒with condition: condition.notify() # 发送信号,恢复线程