def productor (myid,dataqueue,num_thread_per_productor): for i in range(num_thread_per_productor): dataqueue.put('生產者ID:%s ==> 第%s個'%(myid,i)) def consumer (myid,dataqueue,stdoutlock): while True: try: data=dataqueue.get(block=False) except queue.Empty: pass else: with stdoutlock: print ('消費者%s get %s'%(myid,data)) if __name__=='__main__': import queue,threading numproductors=5 num_thread_per_productor=5 numconsumers=3 dataque=queue.Queue() safeprint=threading.Lock() waitfor=[] for i in range(numproductors): productor_thread=threading.Thread(target=productor,args=(i,dataque,num_thread_per_productor)) productor_thread.start() waitfor.append(productor_thread) for i in range(numconsumers): consumer_thread=threading.Thread(target=consumer,args=(i,dataque,safeprint)) consumer_thread.daemon=True consumer_thread.start() for wait_thread in waitfor: wait_thread.join() print (" ----------end-----------")