Event事件,event.wait()可以设置超时时间,超过这个时间,就算没有发送信号,也将执行其他任务
from threading import Thread,Event
import time
event=Event()
def student(name):
print("学生%s正在听课" % name)
event.wait()
print("学生%s正在休息" % name)
def teacher(name):
print("老师%s正在授课" % name)
time.sleep(7)
event.set()
if __name__=="__main__":
stu1=Thread(target=student,args=("ya",))
stu2=Thread(target=student,args=("w",))
stu3=Thread(target=student,args=("l",))
teh1=Thread(target=teacher,args=("Teacher",))
stu1.start()
stu2.start()
stu3.start()
teh1.start()
Event使用,一个线程对服务端进行检测,检测通过后发送事件通知其他线程进行连接
from threading import Thread,Event,currentThread
import time
event=Event()
# event.clear()#恢复event的状态值为False
def conn():
n=0
while not event.is_set():#判断是否被设置
if n==3:
print("%s try too many times"% currentThread().getName())
return
print("%s is try %s" % (currentThread().getName(),n))
event.wait(0.5)#设置等待超时时间
n+=1
print("%s is connected" % currentThread().getName())
def check():
print("%s is checking" % currentThread().getName())
time.sleep(5)
event.set()#设置
if __name__=="__main__":
for i in range(3):
t=Thread(target=conn)
t.start()
t=Thread(target=check)
t.start()