import time from threading import Event, Thread # import time # # is_running = False # # def boot_server(): # global is_running # print("Server is running ......") # time.sleep(2) # print("Server run successfully......") # is_running =True # # def connect_server(): # while True: # if is_running: # print("连接服务器成功!!!") # break # # else: # time.sleep(0.1) # print("error 服务器未启动!!!") # t1 = Thread(target=boot_server) # t1.start() # # t1.join() # 此处要是没有join就会循环报错 ,因为服务器还没有成功启动 # t2 = Thread(target=connect_server) # t2.start() # 用上述例子引出Event # 创建事件(服务器成功事件) boot_event = Event() def boot_server(): print("正在启动服务器......") time.sleep(3) print("服务器启动成功......") # 标记事件已经发生 boot_event.set() def connect_server(): # 等待事件发生 boot_event.wait() print("连接服务器成功......") t1 = Thread(target=boot_server) t1.start() t2 = Thread(target=connect_server) t2.start() # boot_event.clear() # 恢复事件的状态 为False # boot_event.is_set() # 返回事件的状态 # boot_event.wait() # 等待事件的发生 等待事件的状态值被设置(set)成True # boot_event.set() # 将事件的状态值设置为 True