python threading 和 queue 配合操作类的封装

"""
@author: zhangjun.xue
@time: 2020/3/30 14:20
@file: threading_queue.py.py
@desc: 多线程去消费一个队列的例子
"""

import threading
import time
import queue


# # 下面来通过多线程来处理Queue里面的任务:
# def work(q):
#     while True:
#         if q.empty():
#             return
#         else:
#             t = q.get()
#             print("当前线程sleep {} 秒".format(t))
#             time.sleep(t)
#
#
# def main():
#     q = queue.Queue()
#     for i in range(5):
#         q.put(i)  # 往队列里生成消息
#     # 单线程
#     # work(q)
#
#     # 多线程
#     thread_num = 10
#     threads = []
#     for i in range(thread_num):
#         t = threading.Thread(target=work, args=(q,))
#         # args需要输出的是一个元组,如果只有一个参数,后面加,表示元组,否则会报错
#         threads.append(t)
#
#     for i in range(thread_num):
#         threads[i].start()
#     for i in range(thread_num):
#         threads[i].join()


class MyThread(object):

    def __init__(self, thread_num):
        self.q = queue.Queue()
        self.thread_num = thread_num

    def run(self):  # 定义每个线程要运行的函数
        while not self.q.empty():
            t = self.q.get()
            print("当前线程sleep {} 秒".format(t))
            time.sleep(t)

    def make_data(self):
        for i in range(5):
            self.q.put(i)

    def multi_threading_work(self):
        ths = []
        for _ in range(self.thread_num):  # 开启thread_count个线程
            th = threading.Thread(target=self.run)
            th.start()
            ths.append(th)
        for th in ths:
            th.join()


if __name__ == "__main__":
    # start = time.time()
    # main()
    # print('耗时:', time.time() - start)

    start = time.time()
    t = MyThread(5)
    t.make_data()
    print('q.size = ', t.q.qsize())
    t.multi_threading_work()
    print('耗时:', time.time() - start)

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值