MST

星途 面试题库

面试题:Python中优雅退出线程方式的基础实现

在Python中,假设你有一个简单的线程任务,该线程持续打印数字,每打印一次休眠1秒。请使用一种常见的优雅退出线程的方式,使得主线程可以在需要的时候,安全地终止这个线程。请写出实现代码。
19.4万 热度难度
编程语言Python

知识考点

AI 面试

面试题答案

一键面试
import threading
import time


class PrintThread(threading.Thread):
    def __init__(self):
        super().__init__()
        self._stop_event = threading.Event()

    def stop(self):
        self._stop_event.set()

    def run(self):
        num = 0
        while not self._stop_event.is_set():
            print(num)
            num += 1
            time.sleep(1)


if __name__ == "__main__":
    thread = PrintThread()
    thread.start()
    time.sleep(5)  # 主线程等待5秒
    thread.stop()  # 安全地终止线程
    thread.join()  # 等待线程结束