import threading,time,random,queue
q=queue.Queue()
def Producer(name):
count=0
while count<10:
print('%s is making bread...'%name)
time.sleep(random.randrange(3))
print('Producer %s has made bread[%s]'%(name,count))
q.put(count)
count+=1
print('Ok....')
def Consumer(name):
count=0
while count<10:
time.sleep(random.randrange(5))
if not q.empty():
data=q.get()
print('Consumer %s is eating bread[%s]'%(name,data))
else:
print('----no bread anymor----')
count+=1
t1=threading.Thread(target=Producer,args=('A',))
t2=threading.Thread(target=Consumer,args=('B',))
t3=threading.Thread(target=Consumer,args=('C',))
t4=threading.Thread(target=Consumer,args=('D',))
t1.start()
t2.start()
t3.start()
t4.start()
使用task_done与join
import threading,time,random,queue
q=queue.Queue()
def Producer(name):
count=0
while count<10:
print('%s is making bread...'%name)
time.sleep(random.randrange(3))
q.put(count)
print('Producer %s has made bread[%s]'%(name,count))
q.task_done()
#q.join()
count+=1
print('Ok....')
def Consumer(name):
count=0
while count<10:
time.sleep(random.randrange(5))
q.join() #当前面没有触发q.task_done()时会一直处于阻塞状态
data=q.get()
print('\033[1;34mConsumer %s is eating bread[%s]\033[0m'%(name,data))
time.sleep(3)
#q.task_done()
print('\033[1;32mConcumer %s has ate bread[%s]\033[0m'%(name,data))
count+=1
t1=threading.Thread(target=Producer,args=('A',))
t2=threading.Thread(target=Consumer,args=('B',))
t3=threading.Thread(target=Consumer,args=('C',))
t4=threading.Thread(target=Consumer,args=('D',))
t1.start()
t2.start()
t3.start()
t4.start()