python 怎么停止线程,给出代码
时间: 2023-11-12 17:23:37 浏览: 44
好的,以下是一个使用 `Event` 对象来停止线程的示例代码:
```python
import threading
import time
class MyThread(threading.Thread):
def __init__(self):
super().__init__()
self.stop_event = threading.Event()
def run(self):
while not self.stop_event.is_set():
print("Thread is running...")
time.sleep(1)
print("Thread stopped")
def stop(self):
self.stop_event.set()
# 创建线程实例并启动
t = MyThread()
t.start()
# 等待一段时间后停止线程
time.sleep(5)
t.stop()
```
在这个例子中,我们首先定义了一个 `MyThread` 类,继承自 `threading.Thread` 类,并在构造函数中初始化了一个 `Event` 对象 `stop_event`。在 `run()` 方法中,我们使用 `while` 循环来控制线程的运行,只要 `stop_event` 没有被设置,就一直运行,否则就停止。在 `stop()` 方法中,我们设置了 `stop_event`,以便在需要停止线程时调用。
最后,我们创建了一个 `MyThread` 实例 `t` 并启动线程。等待 5 秒后,调用 `t.stop()` 方法来停止线程。