在Python中,要?dú)⒌羲芯€程可以使用threading
模塊提供的方法來實(shí)現(xiàn)。下面是一個(gè)簡單的示例代碼,演示如何停止所有線程:
import threading
# 定義一個(gè)線程類
class MyThread(threading.Thread):
def __init__(self, name):
super().__init__()
self.name = name
def run(self):
while True:
print(f"Thread {self.name} is running")
# 創(chuàng)建多個(gè)線程
threads = []
for i in range(5):
thread = MyThread(str(i))
threads.append(thread)
thread.start()
# 停止所有線程
for thread in threads:
thread.join() # 等待線程執(zhí)行完成
print("All threads are stopped")
在上面的示例中,我們首先創(chuàng)建了5個(gè)線程并啟動(dòng)它們,然后使用join()
方法等待每個(gè)線程執(zhí)行完成。這樣就可以實(shí)現(xiàn)停止所有線程的效果。當(dāng)所有線程執(zhí)行完成后,程序會輸出All threads are stopped
。