1。线程池
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | import threading,time def run(n): s.acquire() #锁线程 print ( "thread--%s starting" % n) time.sleep( 1 ) print ( 'thread---%s done...' % n) s.release() #释放线程 #list=[] s = threading.BoundedSemaphore( 5 ) #信号量。相当于线程池,一次性只能启动5个线程 for i in range ( 50 ): t = threading.Thread(target = run,args = (i,)) t.start() # list.append(t) #for t in list: # t.join() print ( "完了" ) |
事件:红绿灯实例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | import threading,time event = threading.Event() event. set () def lighter(): count = 0 while True : if count> 5 and count< 10 : event.clear() #清除标志位 print ( "lighter is reding...." ) elif count> 10 : event. set () #设置标志位 print ( "lighter is green...." ) count = 0 else : print ( "lighter is green.." ) count + = 1 time.sleep( 1 ) def car(name): while True : if event.is_set(): #判断标志位是否设置。 print ( "[%s] is running" % name) else : print ( "[%s] is stop" % name) event.wait() #等待标志位的变化,如果状态变了,就可以通行了。 print ( "lighte is green going" ) time.sleep( 1 ) l = threading.Thread(target = lighter) l.start() c = threading.Thread(target = car,args = ( 'aodi' ,)) c.start() |
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步