import threading
import queue
import time
# 定义一个生产者
def producer():
count = 0
# 判断队列中任务的数量
while q.qsize()<5:
print(' 第 %s 顿饭 ......',count)
q.put(count)
count+=1
time.sleep(1)
# 定义一个消费者
def consumer(name):
while True:
print("%s 吃了第 %s 饭 " % (name,q.get()))
# 定义一个队列
q = queue.Queue(maxsize=4)
t1 = threading.Thread(target=producer)
t2 = threading.Thread(target=consumer,args=('jibu',))
t1.start()
t2.start()
结果 :
第 %s 顿饭 ...... 0
jibu 吃了第 0 饭
第 %s 顿饭 ...... 1
jibu 吃了第 1 饭
第 %s 顿饭 ...... 2
jibu 吃了第 2 饭
第 %s 顿饭 ...... 3
jibu 吃了第 3 饭
第 %s 顿饭 ...... 4
jibu 吃了第 4 饭
第 %s 顿饭 ...... 5
jibu 吃了第 5 饭
第 %s 顿饭 ...... 6
jibu 吃了第 6 饭
第 %s 顿饭 ...... 7
jibu 吃了第 7 饭
第 %s 顿饭 ...... 8
# 另外,外汇跟单gendan5.com如果供大于求或者求大于供,可以在相对小的一方在增加线程的数量
当然如果需要进一步优化可以让消费者执行完队列中所有任务的时候告诉生产者一声
import threading
import queue
import time
# 定义一个生产者
def producer():
count = 0
# 判断队列中任务的数量
for i in range(5):
print(' 第 %s 顿饭 ......',count)
q.put(count)
count+=1
time.sleep(1)
q.join()
# 定义一个消费者
def consumer(name):
while True:
print("%s 吃了第 %s 饭 " % (name,q.get()))
q.task_done()
print(' 消费者执行完了所有任务 ')
# 定义一个队列
q = queue.Queue(maxsize=4)
t1 = threading.Thread(target=producer)
t2 = threading.Thread(target=consumer,args=('jibu',))
t1.start()
t2.start()
结果
第 0 顿饭 ......
jibu 吃了第 0 饭
消费者执行完了所有任务
第 1 顿饭 ......
jibu 吃了第 1 饭
消费者执行完了所有任务
第 2 顿饭 ......
jibu 吃了第 2 饭
消费者执行完了所有任务
第 3 顿饭 ......
jibu 吃了第 3 饭
消费者执行完了所有任务
第 4 顿饭 ......
jibu 吃了第 4 饭
消费者执行完了所有任务