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)

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章