import datetime, time
import threading
prtnoList = [3, 2, 3, 4, 5, 6, 78, 9, 0, 123, 15, 23, 44, 2, 3, 4, 5, 6, 78, 9, 0, 123, 15, 23, 44, 2, 3, 4, 5, 6, 78, 9, 0, 123, 15, 23, 44]
def print_time(name):
print('1', datetime.datetime.now())
time.sleep(2)
print(name, datetime.datetime.now())
# 方式1:直接用函数实现
#try:
# threads = []
# for name in prtnoList:
# threads.append(threading.Thread(target=print_time, args=(name,)))
# for i in range(0, len(prtnoList), 10):
# sub_threads = threads[i:i+10]
# for thread in sub_threads:
# thread.start()
# if sub_threads.index(thread) == 9:
# thread.join()
# 方式2:重写类
class myThead(threading.Thread):
def __init__(self, theadID, name):
threading.Thread.__init__(self)
self.theadID = theadID
self.name = name
def run(self):
print_time(self.name)
# 线程池
theads = []
for i in prtnoList:
theads.append(myThead(str(i)+'1', str(i)))
# 将线程池中的线程分组执行
for i in range(0, len(theads), 10):
sub_theads = theads[i:i+10]
for thead in sub_theads:
thead.start()
# 等待上一组线程(10个)执行完再执行下一组
if sub_theads.index(thead) == 9:
thead.join()