共計 524 個字符,預計需要花費 2 分鐘才能閱讀完成。
在 Python 中,可以使用 threading 模塊來創建和管理線程。可以通過 Thread 類的 is_alive() 方法來判斷線程的狀態。
下面是一個示例:
import threading
import time
def my_function():
for i in range(5):
print("Running...")
time.sleep(1)
t = threading.Thread(target=my_function)
t.start()
print("Is thread alive?", t.is_alive())
運行以上代碼,會輸出以下結果:
Running...
Is thread alive? True
Running...
Running...
Running...
Running...
可以看到,在線程啟動后,通過 is_alive() 方法判斷線程是否處于活動狀態。如果返回True,則表示線程仍在運行;如果返回False,則表示線程已經結束。
除了使用 is_alive() 方法,還可以使用 threading 模塊中的其他方法,如 enumerate() 方法來獲取所有活動線程的列表,或者使用 active_count() 方法來獲取當前活動線程的數量。
丸趣 TV 網 – 提供最優質的資源集合!
正文完