- 以下案例是通用的带参的类装饰器
- 其他的带参与不带参函数装饰器以及不带参类装饰器案例详见本人博客内其他博文
import threading
import time
class NewThread(object):
def __init__(self, max_thread=500):
self.max_thread = max_thread
def __call__(self, func):
from functools import wraps
@wraps(func)
def wrapper(*args, **kwargs):
while True:
func_thread_active_count = len([i for i in threading.enumerate() if i.name == func.__name__])
if func_thread_active_count <= self.max_thread:
thread = threading.Thread(target=func, args=args, kwargs=kwargs, name=func.__name__)
thread.start()
break
return wrapper
@NewThread(200)
def say(something):
print("say {}!".format(something))
time.sleep(1)
t1 = time.time()
for i in range(2000):
say("hello")
t2 = time.time()
print('运行耗时:' + str(round(t2 - t1, 2)) + ' s')