在Python中,可以使用threading模块来创建和管理线程。在线程中,可以使用Event对象或者Condition对象来实现线程的暂停和恢复。
Event对象来实现线程的暂停和恢复:
Event对象:event = threading.Event()event.wait()来暂停线程,直到收到信号。event.set()来发送信号,恢复线程。示例代码:
import threading
import time
def 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 threading
import time
def 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() # 发送信号,恢复线程