Python笔记24-线程池

参照菜鸟做了一个线程池

from threading import Thread, Lock
from queue import Queue
import time
import random

thread_active = True
thread_lock = Lock()


class MyThread(Thread):
    """自制线程"""

    def __init__(self, thread_name: str, thread_id: int, q: Queue):
        """
        初始化
        :param thread_name:线程名
        :param thread_id: 线程id
        :param q: 队列
        """
        super(MyThread, self).__init__()
        self.thread_name = thread_name
        self.thread_id = thread_id
        self.q = q

    def run(self):
        print(f'开启线程:{self.thread_name} - {self.thread_id}')
        process_date(self.thread_name, self.q)
        print(f'线程结束:{self.thread_name} - {self.thread_id}')


def process_date(thread_name: str, q: Queue):
    while thread_active:
        thread_lock.acquire()

        if q.empty():
            thread_lock.release()
            # pass
        else:
            data = q.get()
            thread_lock.release()
            print(f"线程{thread_name} --- 处理 {data},--{time.ctime(time.time())}")

        time.sleep(random.randint(0, 5))


work_queue = Queue()

thread_names = ['one', 'tow', 'three', 'four', 'five']
# 填充线程列表
thread_list = []
for index, name in enumerate(thread_names):
    t = MyThread(name, index, work_queue)
    thread_list.append(t)
# 启动线程
[t.start() for t in thread_list]
# 填装队列
[work_queue.put(i) for i in range(100)]
# 等待队列被清空
while not work_queue.empty():
    pass

thread_active = False
[t.join() for t in thread_list]

你可能感兴趣的:(Python笔记24-线程池)