python多线程之动态确定线程数

 1 '''
 2 创建线程,也可以动态确定线程数
 3 '''
 4 # encoding: utf-8
 5 
 6 
 7 import threading
 8 import time
 9 import random
10 
11 
12 def print_time(thread_name, step):
13     # python的time.ctime()函数把一个时间戳(按秒计算的浮点数)转化为time.asctime()的形式。
14     # 如果参数未给或者为None的时候,将会默认time.time()为参数。它的作用相当于asctime(localtime(secs))。
15     print(thread_name, ':', time.ctime(time.time()))
16     time.sleep(step)
17 
18 
19 class MyThread(threading.Thread):
20     # 子类的构造函数必须先调用其父类的构造函数,重写run()方法。
21     def __init__(self, thid=None, thname=None, step=0.1):
22         threading.Thread.__init__(self)
23         self.step = step
24         self.thid = thid
25         self.thname = thname
26 
27     def run(self):
28         for i in range(3):
29             print_time(self.thname, self.step)
30             time.sleep(self.step)
31         print('%s结束' % self.thname)
32 
33 print('主线程开始!')
34 
35 
36 threads = []
37 for i in range(10):
38     # 创建出来的线程后面还需要使用,所以使用变量th保存起来,保存到循环之前事先创建好的列表里
39     th = MyThread(thname='线程%d' % i, step=round(random.uniform(0, 1), 2))
40     threads.append(th)
41     th.start()
42 
43 for th in threads:
44     th.join()
45 
46 print('主线程结束!')
原文地址:https://www.cnblogs.com/annatest/p/13356903.html