1. 使用 threading 模块中的 active_count() 方法,该方法返回当前活动线程数,如果返回值大于 1,则说明有多线程在运行。
import threading
if threading.active_count() > 1:
print("有多线程在运行")
else:
print("没有多线程在运行")
2. 在多线程函数中设置一个全局变量,表示线程是否在运行,然后在主程序中检测该变量的值。文章源自爱尚资源教程网-https://www.23jcw.net/6464.html
import threading
import time
is_running = False
def my_thread():
global is_running
is_running = True
# 线程执行的代码
time.sleep(5)
is_running = False
t = threading.Thread(target=my_thread)
t.start()
while True:
if is_running:
print("多线程正在运行")
else:
print("多线程已停止")
break
time.sleep(1)
以上两种方法都可以检测多线程是否在运行,选择哪种方法取决于具体的应用场景。文章源自爱尚资源教程网-https://www.23jcw.net/6464.html 文章源自爱尚资源教程网-https://www.23jcw.net/6464.html
相关文章
版权声明:文章图片资源来源于网络,如有侵权,请留言删除!!!
