多线程+queue队列样例

import threading
from queue import Queue


class ThreadPush(threading.Thread):
    def __init__(self, threadName, my_queue):
        # 继承父类的方法
        super(ThreadPush, self).__init__()
        self.threadName = threadName          # 线程名字
        self.my_queue = my_queue

    def run(self):
        print('启动' + self.threadName)
        while True:
            try:
                id = self.my_queue.get(False)  # False 如果队列为空,抛出异常
            except Exception as e:
                print('队列为空  ', e)
                return
            print(id)


def main():
    my_queue = Queue()
    for i in range(100):
        my_queue.put(i)

    thread_name = []
    for id in range(1, 3):
        name = '线程{}'.format(id)
        thread_name.append(name)

    # 初始化线程
    thread_list = []
    for threadName in thread_name:
        thread = ThreadPush(threadName, my_queue)
        thread_list.append(thread)

    # 启动线程
    for thread in thread_list:
        thread.start()

    # join: 等待线程执行完毕
    for thread in thread_list:
        thread.join()


if __name__ == '__main__':
    main()

posted @ 2020-05-08 16:46  huim  阅读(308)  评论(0编辑  收藏  举报