python 多线程 t.setDaemon(True):

来源:互联网 发布:淘宝网男士加厚衬衣 编辑:程序博客网 时间:2024/05/20 11:25
t.setDaemon(True):#coding=utf-8import threadingfrom time import ctime,sleepdef music(func):    for i in range(5):        print "I was listening to %s. %s" %(func,ctime())        #print threading.currentThread()        sleep(2)def move(func):    for i in range(2):        print "I was at the %s! %s" %(func,ctime())        #print threading.currentThread()        sleep(50)threads = []t1 = threading.Thread(target=music,args=(u'爱情买卖',))threads.append(t1)t2 = threading.Thread(target=move,args=(u'阿凡达',))threads.append(t2)if __name__ == '__main__':    for t in threads:        t.setDaemon(True)        t.start()        #print threading.currentThread()    print "all over %s" %ctime()C:\Python27\python.exe C:/Users/TLCB/PycharmProjects/untitled/mycompany/thread/p7.pyI was listening to 爱情买卖. Thu Sep 07 14:27:02 2017I was at the 阿凡达! Thu Sep 07 14:27:02 2017 all over Thu Sep 07 14:27:02 2017Process finished with exit code 0----------------------------------------------------------------------------------#coding=utf-8import threadingfrom time import ctime,sleepdef music(func):    for i in range(5):        print "I was listening to %s. %s" %(func,ctime())        #print threading.currentThread()        sleep(2)def move(func):    for i in range(2):        print "I was at the %s! %s" %(func,ctime())        #print threading.currentThread()        sleep(50)threads = []t1 = threading.Thread(target=music,args=(u'爱情买卖',))threads.append(t1)t2 = threading.Thread(target=move,args=(u'阿凡达',))threads.append(t2)if __name__ == '__main__':    for t in threads:        #t.setDaemon(True)        t.start()        #print threading.currentThread()    print "all over %s" %ctime()C:\Python27\python.exe C:/Users/TLCB/PycharmProjects/untitled/mycompany/thread/p7.pyI was listening to 爱情买卖. Thu Sep 07 14:24:58 2017I was at the 阿凡达! Thu Sep 07 14:24:58 2017all over Thu Sep 07 14:24:58 2017I was listening to 爱情买卖. Thu Sep 07 14:25:00 2017I was listening to 爱情买卖. Thu Sep 07 14:25:02 2017I was listening to 爱情买卖. Thu Sep 07 14:25:04 2017I was listening to 爱情买卖. Thu Sep 07 14:25:06 2017I was at the 阿凡达! Thu Sep 07 14:25:48 2017Process finished with exit code 0 setDaemon(True)将线程声明为守护线程,必须在start() 方法调用之前设置,如果不设置为守护线程程序会被无限挂起。子线程启动后,父线程也继续执行下去,当父线程执行完最后一条语句print "all over %s" %ctime()后,没有等待子线程,直接就退出了,同时子线程也一同结束。从执行结果来看,子线程(muisc 、move )和主线程(print "all over %s" %ctime())都是同一时间启动,但由于主线程执行完结束,所以导致子线程也终止。 一个布尔值表明是否这个线程是一个daemon 线程(True) or not (False).这个必须是设置在start()被调用前,否则错误会被抛出。它的初始值是从创建线程中继承而来, 主线程不是一个daemon线程 因此所有的线程创建在主线程默认 daemon =FalsesetDaemon()方法。主线程A中,创建了子线程B,并且在主线程A中调用了B.setDaemon(),这个的意思是,把主线程A设置为守护线程,这时候,要是主线程A执行结束了,就不管子线程B是否完成,一并和主线程A退出.这就是setDaemon方法的含义主线程退出,不管子线程是否完成,一并退出但是有时候我们需要的是,只要主线程完成了,不管子线程是否完成,都要和主线程一起退出,这时就可以用setDaemon方法了。