在Python中,可以通过设置线程对象的daemon属性为True来关闭线程。当主线程结束时,所有的守护线程也会随之结束。
另一种方式是使用threading模块提供的Thread类的join()方法。join()方法会阻塞主线程,直到指定的线程结束。通过调用join()方法,可以等待线程执行完毕,然后再继续执行主线程的其他部分。
下面是使用这两种方法关闭线程的示例代码:
方法一:设置线程对象的daemon属性
import threadingimport timedef my_thread(): while True: print("Running...") time.sleep(1)t = threading.Thread(target=my_thread)t.daemon = True # 设置线程为守护线程t.start()# 主线程继续执行其他操作time.sleep(5)print("Main thread finished...")方法二:使用join()方法
import threadingimport timedef my_thread(): while True: print("Running...") time.sleep(1)t = threading.Thread(target=my_thread)t.start()# 主线程等待子线程执行完毕t.join()# 主线程继续执行其他操作print("Main thread finished...")无论使用哪种方法,都可以实现关闭线程的效果。

