python 归纳 (十四)_队列Queue实现生产者消费者

# -*- coding: UTF-8 -*-
"""
多线程的生产者,消费者
使用队列Queue

"""
import Queue
import threading
import time
import random

queue = Queue.Queue(3)  # 创建3个大小的队列

class Producer(threading.Thread):
    """
    生产者,往队列中写数据
    """
    def __init__(self, queue):
        super(Producer, self).__init__()  # 调用父类构造函数
        self.queue = queue

    def run(self):
        while True:
            my_rand_double = random.random()
            self.queue.put(my_rand_double)      # 往队列写数据
            print "producer randonm %f \n" % (my_rand_double)
            time.sleep(2)


class Consumer(threading.Thread):
    """
    消费者,从队列中读取数据
    """
    def __init__(self, queue):
        super(Consumer, self).__init__()
        self.queue = queue

    def run(self):
        while True:
            my_data = self.queue.get()          # 从队列读数据
            print "consumer:",my_data,"\n"
            time.sleep(1)


if __name__ == '__main__':

    print "begin....\n"

    # 启动线程
    Producer(queue).start()
    Consumer(queue).start()
    Consumer(queue).start()

    print "main end....\n"

"""
Out:

begin....

producer randonm 0.321120

consumer: 0.32111958348

main end....

producer randonm 0.340942

consumer: 0.340942161065

producer randonm 0.672640

consumer: 0.672639677729

producer randonm 0.940307

consumer: 0.940307007999

producer randonm 0.497011

consumer: 0.497011018834

"""

猜你喜欢

转载自www.cnblogs.com/sunzebo/p/9612357.html
今日推荐