import threading
import time
def run(n):
print('task ',n)
time.sleep(2)
print('task done',n,threading.current_thread())
# 注意线程数跟机器cpu有关,循环创建线程
# 这个循环是并行的,它并不影响主线程,默认主线程是不会等子线程结束的
mytime = time.time()
tlist = []
for i in range(50):
t = threading.Thread(target=run,args=('t-%s'%i,))
t.start()
tlist.append(t)
# for j in tlist:
# j.join() #等待所有子线程执行完毕后再执行主线程
# t1 = threading.Thread(target=run,args=('t1',))
# #传入一个元组一个参数时必须加逗号
# t2 = threading.Thread(target=run,args=('t2',))
# t1.start()
# t2.start()
# run('t1')
# run('t2')
# 实际上是主线程跟子线程没有影响,是并行的,就是异步的
print('all thread has finished',threading.current_thread(),threading.active_count())
#threading.current_thread() 查看当前线程是否是主线程
# threading.active_count() 查看当前活跃线程的个数,注意如果设置了等待所有线程结束,那么结果就是 1
print(time.time() - mytime) #最终结果应该是两秒左右
# 精确计算线程时间
# 主线程是当前程序,你是看不到的
# 这里是老的启用线程的方法