共計 613 個字符,預計需要花費 2 分鐘才能閱讀完成。
要終止線程池中的線程,可以使用 ThreadPoolExecutor
類的 shutdown()
方法。
下面是一個例子,展示如何使用 ThreadPoolExecutor
創建線程池,并在需要時終止其中的線程:
from concurrent.futures import ThreadPoolExecutor
import time
def task():
print("Thread started")
time.sleep(5)
print("Thread finished")
# 創建線程池
executor = ThreadPoolExecutor(max_workers=5)
# 提交任務到線程池
executor.submit(task)
# 終止線程池中的線程
executor.shutdown()
在上面的例子中,使用 ThreadPoolExecutor
創建了一個最大線程數為 5 的線程池。然后,通過 submit()
方法提交了一個任務到線程池中。最后,調用 shutdown()
方法終止線程池中的線程。
需要注意的是,shutdown()
方法會等待所有已提交的任務執行完畢后再終止線程池中的線程。如果想立即終止線程池中的線程,可以使用 shutdown_now()
方法。
# 立即終止線程池中的線程
executor.shutdown_now()
需要注意的是,使用 shutdown_now()
方法終止線程池中的線程可能會導致未完成的任務被取消。
丸趣 TV 網 – 提供最優質的資源集合!
正文完