可以通过以下方法检查两个线程是否在运行:
1. 使用`is_alive()`方法检查线程是否在运行。该方法返回True表示线程正在运行,返回False表示线程已经停止。文章源自爱尚资源教程网-https://www.23jcw.net/6465.html
2. 使用`threading.enumerate()`方法获取当前所有活动的线程,然后检查目标线程是否在其中。文章源自爱尚资源教程网-https://www.23jcw.net/6465.html
下面是一个示例代码,演示如何使用这两种方法检查线程是否在运行:文章源自爱尚资源教程网-https://www.23jcw.net/6465.html
import threading import time def worker(): print("Worker thread started") time.sleep(5) print("Worker thread finished") # 创建两个线程 t1 = threading.Thread(target=worker) t2 = threading.Thread(target=worker) # 启动线程 t1.start() t2.start() # 检查线程是否在运行 if t1.is_alive(): print("Thread 1 is running") else: print("Thread 1 is not running") if t2.is_alive(): print("Thread 2 is running") else: print("Thread 2 is not running") # 获取当前所有活动的线程 threads = threading.enumerate() # 检查目标线程是否在其中 if t1 in threads: print("Thread 1 is running") else: print("Thread 1 is not running") if t2 in threads: print("Thread 2 is running") else: print("Thread 2 is not running") ``` 输出结果如下: ``` Worker thread started Worker thread started Thread 1 is running Thread 2 is running Thread 1 is running Thread 2 is running Worker thread finished Worker thread finished
文章源自爱尚资源教程网-https://www.23jcw.net/6465.html 文章源自爱尚资源教程网-https://www.23jcw.net/6465.html
相关文章
版权声明:文章图片资源来源于网络,如有侵权,请留言删除!!!