Python 线程优先级,出列顺序,先进先出,先进后出 代码实现

import queue
import threading
import time


exitFlag =0

class myThread(threading.Thread):
    def __init__(self, threadID, name, m_queue):
        threading.Thread.__init__(self)
        self.threadID= threadID               #线程ID
        self.name = name                      #线程名称
        self.m_queue =m_queue                             #出列顺序
    def run(self):
        print("开始线程" + self.name)
        process_data(self.name, self.m_queue)   #执行工作函数
        print("结束线程" + self.name)


#执行工作函数
def process_data(threadName, m_queue):   #传入线程名称以及出列顺序
    while not exitFlag:   #判断线程是否执行完毕
        #获取线程同步锁
        queueLock.acquire()
        if not workQueue.empty():  #判断工作队列是否处理完毕
            data = m_queue.get()
            queueLock.release()   #释放锁
            print("%s processing  %s" % (threadName, data))
        else:
            queueLock.release()   #释放线程同步锁
        time.sleep(1)



#创建线程列表
threadList =["thread-1", "thread-2", "thread-3"]

#需要处理的数据
nameList =["One", "Two", "Three", "Four", "Five", ]
#创建线程同步锁
queueLock =threading.Lock()

#确认出列顺序,先进先出
workQueue =queue.Queue()

#按照先进后出的方式出列
#workQueue =queue.LifoQueue()

#确认出列顺序,按照优先级顺序出列
#workQueue = queue.PriorityQueue()

#创建线程池,稍后会将创建的线程加入线程池中
threads =[]
#创建线程ID
threadID=1


#批量创建新线程
for tName in threadList:
    thread =myThread(threadID, tName, workQueue)  #创建线程,传入线程id,线程名称,出列顺序
    thread.start()                                #线程启动
    threads.append(thread)                        #将线程放入线程池
    threadID +=1                                  #定义下一个线程的id值

#获取线程锁
queueLock.acquire()
for  work in nameList:
    workQueue.put(work)
queueLock.release()    #释放线程锁


#等待队列消息处理完毕
while not  workQueue.empty():
    pass

#通知线程退出
exitFlag =1

#等待线程池线程工作完毕
for t  in threads:
    t.join()

print(nameList)
print("退出主线程.......")

 

posted @ 2021-06-03 03:14  神迹丶  阅读(717)  评论(0编辑  收藏  举报
网站已运行: