守护线程:只起到守护主线程的作用,主线程退出守护线程也跟着退出。
1 import threading,time 2 3 def run(n): 4 print("task",n) 5 time.sleep(2) 6 print("task done",n) 7 8 start_time = time.time() 9 t_objs = [] 10 for i in range(50): 11 t = threading.Thread(target=run,args=("t-%s"%i,)) 12 t.setDaemon(True)#把当前线程设置为守护线程 13 t.start() 14 t_objs.append(t)#为了不阻塞后面线程的启动,不在这里join,先放到一个列表里 15 16 # for t in t_objs:#循环线程实例列表,等待所有线程执行完毕 17 # t.join() 18 19 print("------all threads has finished....",threading.current_thread(),) 20 print("cost:",time.time()-start_time) 21 22 # t1 = threading.Thread(target=run,args=("t1",)) 23 # t2 = threading.Thread(target=run,args=("t2",)) 24 # t1.start() 25 # t2.start() 26 27 # run("t1") 28 # run("t2")