python 使用 threading 多线程模拟 MQ

2019-07-29  本文已影响0人  猿来是八阿哥
# -*- coding: utf-8 -*-
import time
import random
import threading
class PythonMQ(object):
    queue = list()
    a_queue_producer_thread = False
    a_queue_consumer_thread = False
    def __init__(self):
        self.a_queue_producer_thread = threading.Thread(target=self.a_queue_producer)
        self.a_queue_consumer_thread = threading.Thread(target=self.a_queue_consumer)

    def a_queue_producer(self):
        while True:
            self.queue.append(random.randint(1, 1000))
            time.sleep(1)

    def a_queue_consumer(self):
        while True:
            try:
                value = self.queue.pop()
                print 'pop: ' + str(value) + ', len=' + str(len(self.queue))
            except IndexError as ie:
                time.sleep(0.1)

    def start(self):
        self.a_queue_producer_thread.start()
        self.a_queue_consumer_thread.start()

if __name__ == "__main__":
    mq = PythonMQ()
    mq.start()

上一篇下一篇

猜你喜欢

热点阅读