队列
1 #实现一个线程不断生成一个随机数到一个队列中(考虑使用Queue这个模块) 2 # 实现一个线程从上面的队列里面不断的取出奇数 3 # 实现另外一个线程从上面的队列里面不断取出偶数 4 5 import random,threading,time 6 from queue import Queue 7 #Producer thread 8 class Producer(threading.Thread): 9 def __init__(self, t_name, queue): 10 threading.Thread.__init__(self,name=t_name) 11 self.data=queue 12 def run(self): 13 for i in range(10): #随机产生10个数字 ,可以修改为任意大小 14 randomnum=random.randint(1,99) 15 print ("%s: %s is producing %d to the queue!" % (time.ctime(), self.getName(), randomnum)) 16 self.data.put(randomnum) #将数据依次存入队列 17 time.sleep(1) 18 print ("%s: %s finished!" %(time.ctime(), self.getName())) 19 20 #Consumer thread 21 class Consumer_even(threading.Thread): 22 def __init__(self,t_name,queue): 23 threading.Thread.__init__(self,name=t_name) 24 self.data=queue 25 def run(self): 26 while 1: 27 try: 28 val_even = self.data.get(1,5) #get(self, block=True, timeout=None) ,1就是阻塞等待,5是超时5秒 29 if val_even%2==0: 30 print ("%s: %s is consuming. %d in the queue is consumed!" % (time.ctime(),self.getName(),val_even)) 31 time.sleep(2) 32 else: 33 self.data.put(val_even) 34 time.sleep(2) 35 except: #等待输入,超过5秒 就报异常 36 print ("%s: %s finished!" %(time.ctime(),self.getName())) 37 break 38 class Consumer_odd(threading.Thread): 39 def __init__(self,t_name,queue): 40 threading.Thread.__init__(self, name=t_name) 41 self.data=queue 42 def run(self): 43 while 1: 44 try: 45 val_odd = self.data.get(1,5) 46 if val_odd%2!=0: 47 print ("%s: %s is consuming. %d in the queue is consumed!" % (time.ctime(), self.getName(), val_odd)) 48 time.sleep(2) 49 else: 50 self.data.put(val_odd) 51 time.sleep(2) 52 except: 53 print ("%s: %s finished!" % (time.ctime(), self.getName())) 54 break 55 #Main thread 56 def main(): 57 queue = Queue() 58 producer = Producer('Pro.', queue) 59 consumer_even = Consumer_even('Con_even.', queue) 60 consumer_odd = Consumer_odd('Con_odd.',queue) 61 producer.start() 62 consumer_even.start() 63 consumer_odd.start() 64 producer.join() 65 consumer_even.join() 66 consumer_odd.join() 67 print ('All threads terminate!') 68 69 if __name__ == '__main__': 70 main()
1 import threading,queue 2 from time import sleep 3 from random import randint 4 class Production(threading.Thread): 5 def run(self): 6 while True: 7 r=randint(0,100) 8 q.put(r) 9 print("生产出来%s号包子"%r) 10 sleep(1) 11 class Proces(threading.Thread): 12 def run(self): 13 while True: 14 re=q.get() 15 print("吃掉%s号包子"%re) 16 if __name__=="__main__": 17 q=queue.Queue(10) 18 threads=[Production(),Production(),Production(),Proces()] 19 for t in threads: 20 t.start()
1 import threading,time 2 3 li=[1,2,3,4,5] 4 5 def pri(): 6 while li: 7 a=li[-1] 8 print(a) 9 time.sleep(1) 10 try: 11 li.remove(a) 12 except: 13 print('----',a) 14 15 t1=threading.Thread(target=pri,args=()) 16 t1.start() 17 t2=threading.Thread(target=pri,args=()) 18 t2.start()