Python多线程执行队列任务,提高效率开发

#!/usr/bin/env python
# -*- coding:utf-8 -*-
import threading
import time
import queue


# 创建一个线程类并继承threading.Thread
class MyThread(threading.Thread):
    def __init__(self, name):             # 重写init和run方法(参数:线程名称)
        threading.Thread.__init__(self)
        self.Name = name

    def run(self):
        print('开启的线程是:', self.Name)
        while not workQueue.empty():  # 循环队列任务
            index = workQueue.get()
            nowTime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())
            print('%s - %s线程正在执行第%d个任务' % (nowTime, self.Name, index))
        print('结束的线程是:', self.Name)


numList = [i for i in range(0, 100)]   # 任务列表
workQueue = queue.Queue(len(numList))  # 创建队列

if __name__ == '__main__':

    # 填充队列,将任务塞进队列执行
    for num in numList:
        workQueue.put(num)

    # 创建线程
    threads = []
    threadsName = ['一号线程', '二号线程', '三号线程']
    for tName in threadsName:
        thread = MyThread(tName)
        thread.start()             # 执行线程
        threads.append(thread)

    # 等待所有线程执行完成
    for i in threads:
        i.join()

    print('全部执行完成!')

你可能感兴趣的:(python,开发语言)