在Python中,判断多线程是否结束可以通过以下几种方法:
1. 使用 `is_alive()` 方法:
`is_alive()` 方法会返回一个布尔值,如果线程还在运行则返回 `True`,否则返回 `False`。
import threading
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()) 输出:Is thread alive? True
t.join() 等待线程结束
print("Thread is finished.") 输出:Thread is finished.
2. 使用 `join()` 方法:
`join()` 方法会阻塞调用它的线程,直到被监测的线程运行完毕。
import threading
def my_function():
for i in range(5):
print("Running...")
time.sleep(1)
t = threading.Thread(target=my_function)
t.start()
t.join() 等待线程结束
print("Thread is finished.") 输出:Thread is finished.
3. 使用 `enumerate()` 和 `active_count()` 方法:
`enumerate()` 方法可以获取所有活动线程的列表,`active_count()` 方法可以获取当前活动线程的数量。
import threading
def my_function():
for i in range(5):
print("Running...")
time.sleep(1)
t = threading.Thread(target=my_function)
t.start()
for thread in threading.enumerate():
print(f"Thread name: {thread.name}, is alive: {thread.is_alive()}")
t.join() 等待线程结束
print("Thread is finished.") 输出:Thread is finished.
4. 自定义线程类并检查 `running` 标志:
可以创建一个自定义的线程类,并在其中添加一个 `running` 标志来控制线程的运行和结束。
import threading
import random
import time
class MyThread(threading.Thread):
def __init__(self, pass_value):
super(MyThread, self).__init__()
self.running = False
self.value = pass_value
def run(self):
self.running = True
while self.running:
time.sleep(0.25)
rand = random.randint(0, 10)
print(f"{threading.current_thread().name}, {rand}, {self.value}")
if rand == 4:
raise ValueError("Returned 4!")
if __name__ == "__main__":
group1 = []
group2 = []
for g in range(4):
group1.append(MyThread(g))
group2.append(MyThread(g + 20))
for m in group1:
m.start()
print("Now start second wave...")
for p in group2:
p.start()
以上方法可以帮助你判断Python中的多线程是否已经结束。