1。线程池

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("完了")

  事件:红绿灯实例

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()