當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Python Thread is_alive()用法及代碼示例


Python Thread.is_alive() 方法

Thread.is_alive() 方法是 Python 中線程模塊的 Thread 類的內置方法。它使用一個 Thread 對象,並檢查該線程是否處於活動狀態,即它是否仍在運行。此方法在 run() 開始之前返回 True,直到 run() 方法執行之後。

模塊:

    from threading import Thread

用法:

    is_alive()

參數:

  • None

返回值:

這個方法的返回類型是<class 'bool'>, 它返回 True 是線程是活著的,否則返回 False 。

例:

# Python program to explain the
# use of is_alive() method

import time
import threading

def thread_1(i):
    time.sleep(5)
    print('Value by Thread 1:', i)

def thread_2(i):
    print('Value by Thread 2:', i)
    
# Creating three sample threads 
thread1 = threading.Thread(target=thread_1, args=(1,))
thread2 = threading.Thread(target=thread_2, args=(2,))

# Before calling the start(), both threads are not alive
print("Is thread1 alive:", thread1.is_alive())
print("Is thread2 alive:", thread2.is_alive())
print()

thread1.start()
thread2.start()
# Since thread11 is on sleep for 5 seconds, it is alive
# while thread 2 is executed instantly

print("Is thread1 alive:", thread1.is_alive())
print("Is thread2 alive:", thread2.is_alive())

輸出

Is thread1 alive:False
Is thread2 alive:False

Value by Thread 2:2
Is thread1 alive:True
Is thread2 alive:False
Value by Thread 1:1


相關用法


注:本文由純淨天空篩選整理自 Python Thread Class | is_alive() Method with Example。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。