m开头的网站开发工具,网站开发 托管合同,asp 网站开发 软件,省住房和城乡建设厅需求#xff1a;主线程创建子线程和键盘输入监听线程#xff0c;然后等待它们退出。当用户输入 q 后#xff0c; 子线程会收到停止信号并退出#xff0c;键盘输入监听线程也会退出#xff0c;最终主线程退出。
import threading
import time
import keyboardclass Worker…需求主线程创建子线程和键盘输入监听线程然后等待它们退出。当用户输入 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(fWorker thread {thread_id} 已经启动了~)while not self.stop_event.is_set():print(fWorker thread {thread_id} 正在运行中~)time.sleep(1)print(fWorker 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(fStopping worker thread {worker_id}...)stop_event.set()breakif __name__ __main__:# 创建线程事件stop_event threading.Event()# 创建子线程并传递线程事件worker_thread WorkerThread(stop_event)# 创建键盘输入监听线程keyboard_thread threading.Thread(targetkey_listener, args(stop_event,))# 启动子线程和键盘输入监听线程worker_thread.start()keyboard_thread.start()# 等待子线程和键盘输入监听线程退出worker_thread.join()keyboard_thread.join()# 主线程退出main_thread_id threading.main_thread().identprint(fMain 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(targetkey_listen, args(stop_event,))worker_thread.start()keyboard_thread.start()worker_thread.join()keyboard_thread.join()print(主线程退出)