from queue import Queue from threading import Thread class mydownloader(Thread): def __init__(self,queue): Thread.__init__(self) self.queue = queue def run(self): i = 0 mydict={} #print("当前队列容量{}".format(self.queue.qsize())) while True: if self.queue.qsize()==0: print("完美收官!") break print("当前队列容量{}\r\n".format(self.queue.qsize())) print("处理第{}波次".format(i)) mydict = self.queue.get() print("我爱{},他今年芳龄{}".format(mydict["name"],mydict["age"])) print("处理后队列容量{}".format(self.queue.qsize())) i+=1 def main(): queue = Queue() queue.put({"name": "程劲", "age": 21}) queue.put({"name": "陈培昌", "age": 19}) queue.put({"name": "厉智", "age": 31}) queue.put({"name": "徐晓冬", "age": 40}) queue.put({"name": "奥", "age": 36}) for i in range(2): cpc = mydownloader(queue) cpc.daemon=True cpc.start() queue.join() #if __name__=="__main__": main()
结果:
当前队列容量5
处理第0波次
我爱程劲,他今年芳龄21
处理后队列容量4
当前队列容量4
当前队列容量4
处理第1波次
我爱陈培昌,他今年芳龄19
处理后队列容量3
当前队列容量3
处理第0波次
处理第2波次我爱厉智,他今年芳龄31
处理后队列容量2我爱徐晓冬,他今年芳龄40
当前队列容量1
处理后队列容量1
当前队列容量1
处理第3波次
我爱奥,他今年芳龄36
处理第1波次处理后队列容量0
完美收官!
爬虫相关基础技术铺垫---多线程Thread和队列Queue应用
原文:https://www.cnblogs.com/saintdingspage/p/10575779.html