首页 > 编程语言 > 详细

多线程+queue队列样例

时间:2020-05-08 18:12:10      阅读:34      评论:0      收藏:0      [点我收藏+]
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()

多线程+queue队列样例

原文:https://www.cnblogs.com/huim/p/12851437.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!