python(生产者消费者 threading,time,queue)

# Author: Sooele
import threading,time
import queue
q = queue.Queue(maxsize=10)  #生产者maxsize表示队列最大为10
def Producer(name):   #生产者
    count = 1       #开始为1
    while True:
        q.put("试试%s" % count)
        print("生产了多少",count)
        count +=1       #+1
def Consumer(name):#消费者
    while q.qsize()>0:
        print("[%s]取到[%s]并且吃了它..." %(name,q.get()))
        time.sleep(1)
p = threading.Thread(target=Producer,args=("ssbb",))   #生产者
c = threading.Thread(target=Consumer,args=("qqaaa",))   #消费者1
c1 = threading.Thread(target=Consumer,args=("uuoo",))   #消费者2
p.start()
c.start()
c1.start()



 
版本2

# Author: Sooele
import threading,time
import queue
q = queue.Queue(maxsize=10)
def Producer(name):   #生产者
    count = 1
    while True:
        q.put("试试%s" % count)
        print("生产了多少",count)
        count +=1
        time.sleep(2)
def Consumer(name):#消费者
    #while q.qsize()>0:
    while True:
        print("[%s]取到[%s]并且吃了它..." %(name,q.get()))
        time.sleep(1)
p = threading.Thread(target=Producer,args=("ssbb",))   #生产者
c = threading.Thread(target=Consumer,args=("qqaaa",))   #消费者1
c1 = threading.Thread(target=Consumer,args=("uuoo",))   #消费者2
p.start()
c.start()
c1.start()

说点什么

avatar
  Subscribe  
提醒