在 Python 中,可以使用 threading
模块来创建和管理线程。要暂停线程,可以使用 threading.Event()
对象来实现。
下面是一个示例代码,演示了如何暂停和恢复两个线程:
import threading import time # 创建一个 Event 对象,用于暂停和恢复线程 pause_event = threading.Event() # 线程函数1 def thread1_func(): while True: print("Thread 1 is running") time.sleep(1) # 检查 Event 对象状态,如果处于暂停状态,则线程进入等待状态 pause_event.wait() # 线程函数2 def thread2_func(): while True: print("Thread 2 is running") time.sleep(1) # 检查 Event 对象状态,如果处于暂停状态,则线程进入等待状态 pause_event.wait() # 创建并启动两个线程 thread1 = threading.Thread(target=thread1_func) thread2 = threading.Thread(target=thread2_func) thread1.start() thread2.start() # 暂停线程 pause_event.clear() time.sleep(3) # 恢复线程 pause_event.set() # 等待线程执行完毕 thread1.join() thread2.join()
在上面的代码中,创建了一个 Event
对象 pause_event
,并在每个线程函数中使用 wait()
方法来检查该对象的状态。当 pause_event
处于暂停状态(即 clear()
被调用),线程会进入等待状态;当 pause_event
处于激活状态(即 set()
被调用),线程会继续执行。
通过调用 clear()
方法,可以暂停线程;通过调用 set()
方法,可以恢复线程的执行。在上面的示例中,线程会在启动后暂停 3 秒钟,然后再恢复执行,最后等待线程执行完毕。