day10_主线程等待子线程的两种方式
import threading,time
def axb(name):
time.sleep(1)
print('哈哈',name)
for i in range(10):
t = threading.Thread(target = axb,args = (i,)) # 实例化一个线程,启动一个线程,10个子线程一起执行axb函数,先暂停1秒
t.start()
print('game over')
# 有1个主线程,10个子线程,先执行主线程,主线程创建完10个子线程,不暂停直接输出,子线程要暂停1秒再执行axb里面的代码才输出
如果在for循环里写t.join(),只等待最后一个线程,线程和线程之间是相互独立的
import threading
import time
def down_load():
time.sleep(5)
print('运行完了')
def movie():
time.sleep(1)
print('看电影')
start_time = time.time()
for i in range(10):
t = threading.Thread(target=down_load)
t.start()
for j in range(5):
t = threading.Thread(target=movie)
t.start()
print(threading.activeCount()) # 查看当前线程数,打印出16(1个主线程,15个子线程)
print(threading.current_thread()) # 查看当前线程,打印出<_MainThread(MainThread, started 35028)>
end_time = time.time()
# 运行时先打印end_time - start_time,然后运行5次看电影,再运行10次运行完了
print(end_time - start_time)
主线程等待的两种方式(第一种,比较麻烦):
import threading
import time
def movie():
time.sleep(1)
print('看电影')
thread_list = []
start_time = time.time()
for j in range(5):
t = threading.Thread(target=movie)
t.start()
thread_list.append(t)
for thread in thread_list:
thread.join() # 主线程等待子线程
print(threading.activeCount()) # 查看当前线程数,打印出1,主线程等待五个子线程都运行完了
print(threading.current_thread()) # 查看当前线程,打印出<_MainThread(MainThread, started 29960)>
end_time = time.time()
# 运行时先运行5次看电影,然后主线程往下走,代码一次运行
print(end_time - start_time)
主线程等待的两种方式(第二种,根据当前线程数判断,如果当前线程数等于1,证明子线程都执行完了,不用定义list,也不用循环list,定义一个死循环,什么都不做):
import threading
import time
def movie():
time.sleep(1)
print('看电影')
start_time = time.time()
for j in range(5):
t = threading.Thread(target=movie)
t.start()
while threading.activeCount() != 1: # !=1让它继续循环,直到子线程结束运行
pass
print(threading.activeCount()) # 查看当前线程数,打印出1,主线程等待五个子线程都运行完了
print(threading.current_thread()) # 查看当前线程,打印出<_MainThread(MainThread, started 29960)>
end_time = time.time()
# 运行时先运行5次看电影,然后主线程往下走,代码一次运行
print(end_time - start_time)