网站排版尺寸互联网广告营销是什么
需求:主线程创建子线程和键盘输入监听线程,然后等待它们退出。当用户输入 'q' 后, 子线程会收到停止信号并退出,键盘输入监听线程也会退出,最终主线程退出。
import threading
import time
import keyboardclass WorkerThread(threading.Thread):def __init__(self, stop_event):super().__init__()self.stop_event = stop_eventdef run(self):thread_id = threading.get_ident() # 获取线程 IDprint(f"Worker thread {thread_id} 已经启动了~")while not self.stop_event.is_set():print(f"Worker thread {thread_id} 正在运行中~")time.sleep(1)print(f"Worker thread {thread_id} 已经停止~")def key_listener(stop_event):lock = threading.Lock() # 创建互斥锁print("Press 'q' to stop the thread...")while True:if keyboard.is_pressed('q'):with lock: # 使用互斥锁来保护共享资源的访问worker_id = worker_thread.identprint(f"Stopping worker thread {worker_id}...")stop_event.set()breakif __name__ == '__main__':# 创建线程事件stop_event = threading.Event()# 创建子线程并传递线程事件worker_thread = WorkerThread(stop_event)# 创建键盘输入监听线程keyboard_thread = threading.Thread(target=key_listener, args=(stop_event,))# 启动子线程和键盘输入监听线程worker_thread.start()keyboard_thread.start()# 等待子线程和键盘输入监听线程退出worker_thread.join()keyboard_thread.join()# 主线程退出main_thread_id = threading.main_thread().identprint(f"Main thread {main_thread_id} exiting.")
主线程创建子线程和键盘输入监听线程,然后等待它们退出。当用户输入 0 后,子线程会收到停止信号并退出,键盘输入监听线程也会退出,最终主线程退出。
import threading
import timeclass WorkerThread(threading.Thread):def __init__(self, stop_event):super().__init__()self.stop_event = stop_eventdef run(self):while not self.stop_event.is_set():print("线程在运行~")time.sleep(1)print("线程已经结束~")def key_listen(stop_event):while True:command = input("请输入指令")if command == "0":stop_event.set()worker_thread.join()print("线程已经完全结束~")breakif __name__ == '__main__':stop_event = threading.Event()worker_thread = WorkerThread(stop_event)keyboard_thread = threading.Thread(target=key_listen, args=(stop_event,))worker_thread.start()keyboard_thread.start()worker_thread.join()keyboard_thread.join()print("主线程退出")