面试题答案
一键面试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() # 等待线程结束