#!/usr/bin/python
#coding=utf-8
#http://docs.python.org/library/threading.html
import threading, time, random

from collections import deque
class 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 thread
def 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()

相关文章:

  • 2022-12-23
  • 2021-09-11
  • 2021-09-29
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-11-07
  • 2022-12-23
猜你喜欢
  • 2021-11-05
  • 2021-11-08
  • 2021-10-12
  • 2022-12-23
  • 2021-10-26
  • 2022-12-23
相关资源
相似解决方案