#!/usr/bin/python#coding=utf-8#http://docs.python.org/library/threading.htmlimport threading, time, randomfrom collections import dequeclass threadPool(object): def __init__(self, maxNum = 10): self.maxNum = maxNum self.deque = deque() def push(self, target, args = None): t = threading.Thread(target=target, args=args) self.deque.append(t) def run(self): while True: #隊列沒有進程就退出 if len(self.deque) == 0: break if threading.activeCount() < self.maxNum + 1: t = self.deque.popleft() t.start() time.sleep(0.00001) #減少CPU的損耗# Define a function for the threaddef print_time( threadName, delay): print "%s: %s\t%s" % ( threadName, time.ctime(time.time()) , delay) time.sleep(delay) if __name__ == '__main__': pool = threadPool(2) for i in range(1000): pool.push(target=print_time, args=("Thread-%d" % i, random.randint(1, 100) * 0.001)) pool.run()