判断线程是否执行完毕,不是等待执行完毕
时间: 2023-11-26 14:02:43 浏览: 71
判断线程是否执行完毕可以通过以下两种方式实现:
1. 使用thread.join()方法:该方法会阻塞当前线程,直到被调用join()方法的线程执行完毕。
例子代码如下:
```python
import threading
def worker():
print("Worker started")
# do some work here...
print("Worker finished")
t = threading.Thread(target=worker)
t.start()
# 判断线程是否执行完毕
if t.is_alive():
print("Thread is still running")
else:
print("Thread has finished")
t.join()
```
2. 使用threading.active_count()方法:该方法会返回当前活跃的线程数,如果只有主线程一个活跃线程,那么可以判断其它线程是否执行完毕。
例子代码如下:
```python
import threading
def worker():
print("Worker started")
# do some work here...
print("Worker finished")
t = threading.Thread(target=worker)
t.start()
# 判断线程是否执行完毕
while threading.active_count() > 1:
print("Thread is still running")
print("Thread has finished")
```
这两种方式都可以判断线程是否执行完毕,但是第一种方式更加直观易懂,适合在需要等待线程执行完毕的场景中使用。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)