'''知识补充---for循环没有作用域''' # s = 'abcdef' # a = 0 # for i in s: # a+=1 # print(i=='f') # 循环最后一次i指向的是f,a是6 # print(a==6) import threading import time ''' setDaemon(True):将线程声明为守护线程,必须在start()方法调用之前设置。这个方法基本和join是相反的。 当我们在程序运行中,执行一个主线程,如果主线程又创建一个子线程,主线程和子线程就分兵两路,分别运行,那么当主线程完成 想退出时,会检验子线程是否完成。如果子线程未完成,则主线程会等待子线程完成后再退出。但是有时候我们需要的是只要主线程 完成了,不管子线程是否完成,都要和主线程一起退出,这时就可以用setDaemon()方法 ''' def music(): print('begin to listen music %s' % time.ctime()) time.sleep(3) print('stop to listen music %s' % time.ctime()) def game(): print('begin to play game %s' % time.ctime()) time.sleep(5) print('stop to play game %s' % time.ctime()) l = [] t1 = threading.Thread(target=music) t2 = threading.Thread(target=game) l.append(t1) l.append(t2) # if __name__ == '__main__': # for i in l: # i.setDaemon(True) # 一定要在所有start()之前设置 # for t in l: # t.start() # print('ending...') # begin to listen music Tue Jun 1 18:05:33 2021 # begin to play game Tue Jun 1 18:05:33 2021 # ending... # if __name__ == '__main__': # t1.setDaemon(True) # for t in l: # t.start() # print('ending...') # begin to listen music Tue Jun 1 18:06:49 2021 # begin to play game Tue Jun 1 18:06:49 2021 # ending... # stop to listen music Tue Jun 1 18:06:52 2021 # stop to play game Tue Jun 1 18:06:54 2021 # if __name__ == '__main__': # t2.setDaemon(True) # for t in l: # t.start() # print('ending...') # begin to listen music Tue Jun 1 18:08:13 2021 # begin to play game Tue Jun 1 18:08:13 2021 # ending... # stop to listen music Tue Jun 1 18:08:16 2021 '''其它方法''' # if __name__ == '__main__': # t1.run() # 线程被cpu调度后自动执行线程对象的run方法 # t1.start() # print(t1.is_alive()) # 判断线程是否在运行 # print(t1.getName()) # Thread-1 # print(t2.getName()) # Thread-2 # t1.setName('第一个线程') # print(t1.getName()) # 第一个线程