import threading
import queue
import time
# 生产者类
class Producer(threading.Thread):
def __init__(self, queue):
threading.Thread.__init__(self)
self.queue = queue
def run(self):
for i in range(10):
print(f"生产者生产了: {i}")
self.queue.put(i)
time.sleep(1)
# 消费者类
class Consumer(threading.Thread):
def __init__(self, queue):
threading.Thread.__init__(self)
self.queue = queue
def run(self):
while True:
item = self.queue.get()
if item is None:
break
print(f"消费者消费了: {item}")
self.queue.task_done()
if __name__ == '__main__':
q = queue.Queue()
producer = Producer(q)
consumer = Consumer(q)
producer.start()
consumer.start()
producer.join()
q.put(None) # 向队列中放入结束标志
consumer.join()
- 代码说明:
- Queue模块:
queue.Queue
是Python标准库中用于线程安全队列的类。它提供了诸如 put
(放入元素)、get
(取出元素)和 task_done
(标记任务完成)等方法,这些方法都是线程安全的,适合在生产者 - 消费者模型中使用。
- 生产者类
Producer
:
- 继承自
threading.Thread
类,在 run
方法中,持续生成数字并使用 queue.put
方法将数字放入队列中,每次生成后休眠1秒。
- 消费者类
Consumer
:
- 同样继承自
threading.Thread
类,在 run
方法中,使用 queue.get
方法从队列中取出元素并打印。while True
循环确保消费者持续运行,直到遇到 None
作为结束标志。queue.task_done
方法用于通知队列任务已完成。
- 主程序:
- 创建了一个队列
q
,然后分别实例化生产者和消费者线程。启动这两个线程后,等待生产者线程完成,然后向队列中放入 None
作为结束标志,最后等待消费者线程完成。这样就实现了一个简单的线程安全的生产者 - 消费者模型。