#!/usr/bin/python#Coding:utf-8ImportThreadingImport TimeImportQueueImportRandom#Multithreading ComprehensiondefPrint_time (threadname,delay,counter): whileCounter:time.sleep (Delay)Print "%s:%s\n"%(Threadname,time.ctime (Time.time ())) counter-=1defMain ():Print 'All start at:', Time.ctime () Threads= [] forIinchRange (5): Name='thread-%d'%i t= Threading. Thread (target=print_time,args= (name,1,3)) Threads.append (t) forJinchThreads:j.start () forKinchThreads:k.join ()Print 'All do at :', Time.ctime ()#Queue Queuing Module UnderstandingQueue = Queue.queue (10)defmain2 (): Thread1= Threading. Thread (target=producer) Thread2= Threading. Thread (target=customer) Thread1.start () Thread2.start ()defproducer (): Nums= Range (100) whileTrue:num=Random.choice (nums)ifqueue.full ():Print 'inventory is full \ n' Else: Queue.put (num)Print "Product%d\n"%Num Time.sleep (1)defcustomer ():#Global Queue whileTrue:ifqueue.empty ():Print 'inventory is empty \ n' Else: Num=Queue.get ()Print 'consumption:%d\n'%Num Time.sleep (1)#using the queue module to control the number of threads running (concurrency type)Queue =Queue.queue ()defque_init (): Lists= Range (50) forIinchlists:queue.put (i)defprint_num (num):PrintNumdefmain3 (): Que_init () Thread_num= 10 while notqueue.empty (): Threads= [] ifQueue.qsize () >Thread_num:threads_number=Thread_numElse: Threads_number=queue.qsize () forIinchRange (threads_number): Das=queue.get () T= Threading. Thread (target=print_num,args=(Das,)) Threads.append (t) forJinchThreads:j.start () forKinchThreads:j.join ()Print '\ n'if __name__=='__main__': #print_time (' Thread1 ', 1,10)Main3 ()
Python example-Threads and queues