import threading,time
classBoss(threading.Thread):defrun(self):
print("BOSS:今晚大家都要加班到22:00。")
print(event.isSet())
event.set()# set flag
time.sleep(5)
print("BOSS:<22:00>可以下班了。")
print(event.isSet())
event.set()
classWorker(threading.Thread):defrun(self):
event.wait() #等待event的flag被set,才执行下面的代码
print("Worker:哎……命苦啊!")
time.sleep(1)
event.clear()#还原到flag没有被set的状态
event.wait()
print("Worker:OhYeah!")
if __name__=="__main__":
event=threading.Event()#创建一个同步对象
threads=[]
for i in range(5):
threads.append(Worker())
threads.append(Boss())
for t in threads:
t.start()
for t in threads:
t.join()
import threading,time
classmyThread(threading.Thread):defrun(self):if semaphore.acquire():
print(self.name)
time.sleep(5)
semaphore.release()
if __name__=="__main__":
semaphore=threading.Semaphore(5)
thrs=[]
for i in range(100):
thrs.append(myThread())
for t in thrs:
t.start()