python threading线程如何停止
时间: 2023-11-11 14:07:03 浏览: 39
Python的threading模块提供了一些方法来控制线程的运行状态,下面介绍几种停止线程的方法:
1. 设置flag,使线程自动退出:在线程函数中使用一个flag来控制线程是否继续执行,当flag为False时,跳出线程函数,从而实现线程的停止。
```python
import threading
import time
def worker(stop_event):
while not stop_event.is_set():
print('working...')
time.sleep(1)
stop_event = threading.Event()
t = threading.Thread(target=worker, args=(stop_event,))
t.start()
time.sleep(5)
stop_event.set()
print('stop thread')
```
2. 使用Thread对象的join()方法:调用线程对象的join()方法会阻塞当前线程,直到被调用的线程完成运行才会继续执行。
```python
import threading
import time
def worker():
while True:
print('working...')
time.sleep(1)
t = threading.Thread(target=worker)
t.start()
time.sleep(5)
t.join()
print('stop thread')
```
3. 使用Thread对象的terminate()方法:这种方法可以强制杀死线程,但是不推荐使用,因为它可能会产生一些意想不到的问题。
```python
import threading
import time
def worker():
while True:
print('working...')
time.sleep(1)
t = threading.Thread(target=worker)
t.start()
time.sleep(5)
t.terminate()
print('stop thread')
```