python例子-线程和队列
#!/usr/bin/python #coding:utf-8 import threading import time import Queue import random #多线程理解 def print_time(threadName,delay,counter): while counter: time.sleep(delay) print "%s:%s\n" %(threadName,time.ctime(time.time())) counter -=1 def main(): print 'All start at:',time.ctime() threads = [] for i in range(5): name = 'Thread-%d' % i t = threading.Thread(target=print_time,args=(name,1,3)) threads.append(t) for j in threads: j.start() for k in threads: k.join() print 'All Done at: ',time.ctime() # Queue 队列模块理解 queue = Queue.Queue(10) def main2(): thread1 = threading.Thread(target=producer) thread2 = threading.Thread(target=customer) thread1.start() thread2.start() def producer(): nums = range(100) while True: num = random.choice(nums) if queue.full(): print '库存已满\n' else: queue.put(num) print "产品 %d\n" % num time.sleep(1) def customer(): #global queue while True: if queue.empty(): print '库存已空\n' else: num = queue.get() print '消费:%d\n' % num time.sleep(1) # 使用Queue模块控制线程运行数量(并发型) queue = Queue.Queue() def que_init(): lists = range(50) for i in lists: queue.put(i) def print_num(num): print num def main3(): que_init() thread_num = 10 while not queue.empty(): threads = [] if queue.qsize() > thread_num: threads_number = thread_num else: threads_number = queue.qsize() for i in range(threads_number): das = queue.get() t = threading.Thread(target=print_num,args=(das,)) threads.append(t) for j in threads: j.start() for k in threads: j.join() print '\n' if __name__ == '__main__': #print_time('thread1',1,10) main3()