Python 多线程 行列 示例

Python 多线程 队列 示例

Python3,开一个线程,间隔1秒把一个递增的数字写入队列,再开一个线程,从队列中取出数字并打印到终端

1 #! /usr/bin/env python3 2 3 import time 4 import threading 5 import queue 6 7 # 一个线程,间隔一定的时间,把一个递增的数字写入队列 8 # 生产者 9 class Producer(threading.Thread): 10 11 def __init__(self, work_queue): 12 super().__init__() 13 self.work_queue = work_queue 14 15 def run(self): 16 num = 1 17 while True: 18 self.work_queue.put(num) 19 num = num+1 20 time.sleep(1) 21 22 # 一个线程,从队列取出数字,并显示到终端 23 class Printer(threading.Thread): 24 25 def __init__(self, work_queue): 26 super().__init__() 27 self.work_queue = work_queue 28 29 def run(self): 30 while True: 31 num = self.work_queue.get() 32 print(num) 33 34 def main(): 35 work_queue = queue.Queue() 36 37 producer = Producer(work_queue) 38 producer.daemon = True 39 producer.start() 40 41 printer = Printer(work_queue) 42 printer.daemon = True 43 printer.start() 44 45 work_queue.join() 46 47 if __name__ == '__main__': 48 main() 49