场景:
有做包子和吃包子两个人
吃包子的时候得等到做包子的人做好才可以
这也是我们所常说的生产者和消费者模型
import threading,time
from random import randint
class Producer(threading.Thread):
def run(self):
global L
while True:
val=randint(0,100)
print('生产者',self.name,":Append"+str(val),L)#做包子
if lock_con.acquire():#做包子的时候线程锁住,做完了之后唤醒吃包子的线程
L.append(val)
lock_con.notify()
lock_con.release()
time.sleep(3)
class Consumer(threading.Thread):
def run(self):
global L
while True:
lock_con.acquire()
if len(L)==0:
lock_con.wait()
print('ok')
print('消费者',self.name,":Delete"+str(L[0]),L)#吃包子
del L[0]
lock_con.release()
time.sleep(1)
if __name__=='__main__':
L=[]#包子容器
lock_con = threading.Condition()
threads=[]
for i in range(5):
threads.append(Producer())
threads.append(Consumer())
for t in threads:
t.start()
for t in threads:
t.join()