昨天复习了线程以及线程的同步,今天复习线程优先级队列 使用queue 之前讲过 queue.Queue是服务线程的 而Queue 是服务进程的,这个要注意。
线程优先级队列示例如下:
from threading import Thread,Lock
from queue import Queue
import time
class myThread(Thread):
def __init__(self,name,q):
super().__init__()
self.name= name
self.q = q
def run(self):
print(f'{self.name}在运行')
task(self.name,self.q)
print(f'{self.name}退出')
def task(name,tq):
q_lock.acquire()
print(q.empty())
if not q.empty():
print(f'{name}'+tq.get())
q_lock.release()
else:
q_lock.release()
time.sleep(1)
thread_list = ['线程-','线程二','线程三','线程四','线程五']
threads =[]
q = Queue(10)
q_lock = Lock()
for threaName in thread_list:
thread=myThread(threaName,q)
thread.start()
threads.append(thread)
q_lock.acquire()
for i in range(5,10):
q.put('data'+str(i))
q_lock.release()
while not q.empty():
pass
for thread in thread_list:
thread.join()
运行结果如下:
好了 ,今天就复习到这里,明天使用多线程爬取豆瓣TOP250
加油