实例实例Python终止线程的方法有以下几种:使用 .Thread.join() 方法:
实例
Python终止线程的方法有以下几种:
1. 使用 threading.Thread.join() 方法:
该方法可以让线程在指定时间内等待,如果超过指定时间,线程将被强制终止。
代码实例:
import threading
def thread_function():
print("Thread starting")
thread = threading.Thread(target=thread_function)
thread.start()
# 等待 5 秒
thread.join(5)
2. 使用 threading.Thread.setDaemon() 方法:
该方法可以将线程设置为守护线程,当主线程终止时,守护线程也会被强制终止。
代码实例:
import threading
def thread_function():
print("Thread starting")
thread = threading.Thread(target=thread_function)
thread.setDaemon(True)
thread.start()
3. 使用 threading.Event() 方法:
该方法可以让线程等待某个事件的发生,如果等待超时,线程将被强制终止。
代码实例:
import threading
def thread_function():
print("Thread starting")
event = threading.Event()
thread = threading.Thread(target=thread_function, args=(event,))
thread.start()
# 等待 5 秒
event.wait(5)
4. 使用 threading.Thread.is_alive() 方法:
该方法可以检测线程是否存活,如果线程已经终止,则返回 False,可以调用 threading.Thread.join() 方法来终止线程。
代码实例:
import threading
def thread_function():
print("Thread starting")
thread = threading.Thread(target=thread_function)
thread.start()
# 检测线程是否存活
if thread.is_alive():
# 终止线程
thread.join()
本站系公益性非盈利分享网址,本文来自用户投稿,不代表边看边学立场,如若转载,请注明出处
评论列表(43条)