zoukankan      html  css  js  c++  java
  • python线程-----setDaemen(True) 和 join()方法

    一、setDaemon(True)

    1、改方法将线程申明为守护线程,必须在start()方法之前设置

    2、当我们在程序运行时,执行一个主线程,如果主线程又创建一个子线程,那么子线程和主线程兵分两路,分别运行;那么当主线程运行结束时会检查子线程是否完成,如果子线程未完成,那么主线程会等待子线程完成后一起退出

    3、但是有时候不想等待子线程是否完成,只要主线程完成就直接退出,这时候就可以将子线程设置为守护线程,子线程守护主线程,不管自己的死活(当舔狗),于是就可以给子线程打上setDeamon()的标签。这样看到setDeamon()标志的线程就知道它是主线程舔狗

    import threading
    import time
    from time import ctime
    def sing():
        print("begin to sing            %s" % time.ctime())
        time.sleep(3)
        print("stop to sing             %s" % time.ctime())
        
    def jump():
        print("begin to jump            %s" % time.ctime())
        time.sleep(5)
        print("stop to jump             %s" % time.ctime())
    
    threads = []
    t1 = threading.Thread(target = sing)
    t2 = threading.Thread(target = jump)
    
    threads.append(t1)    
    threads.append(t2)       
        
            
    if __name__ == '__main__':
        t2.setDaemon(True)#将t2设置成舔狗线程,
        for t in threads:
            
            t.start()
        print("all over   %s" % ctime())
    

    t2没有打印出stop,因为主线程和t1一起结束了。t1不是舔狗,所以主线程等待着t1一起结束线程,而不管t2怎么样。

    如果将t1也设置成守护线程那么得到的图是

    if __name__ == '__main__':
        t1.setDaemon(True)
        t2.setDaemon(True)
        for t in threads:
            
            t.start()
        print("all over   %s" % ctime())
    

    主线程和begin一起开始,然后直接结束主线程,不管t1 2是否执行完毕

    二、join()方法

    在子线程完成运行之前,这个子线程的父类进程一直被阻塞

    import threading
    import time
    from time import ctime
    def sing():
        print("begin to sing            %s" % time.ctime())
        time.sleep(3)
        print("stop to sing             %s" % time.ctime())
        
    def jump():
        print("begin to jump            %s" % time.ctime())
        time.sleep(5)
        print("stop to jump             %s" % time.ctime())
    
    threads = []
    t1 = threading.Thread(target = sing)
    t2 = threading.Thread(target = jump)
    
    threads.append(t1)    
    threads.append(t2)       
        
            
    if __name__ == '__main__':
    
        for t in threads:
            t.start()
            t1.join()#先执行子线程t1的内容,
            
        print("all over   %s" % ctime())
    

    t1.join(),让代码先执行t1的内容,不执行主线程的print(),主线程一直被阻塞,直到t1完成之后才开始执行主线程

    2.只有当t1执行完毕后,才执行主线程和t2子线程

  • 相关阅读:
    angular js 删除及多条删除
    angular js 页面修改数据存入数据库
    angular js 页面添加数据保存数据库
    angular js 分页
    内置函数和匿名函数
    装饰器,迭代器,生成器
    函数的进阶
    函数
    文件操作
    列表,字典
  • 原文地址:https://www.cnblogs.com/hyxk/p/11281153.html
Copyright © 2011-2022 走看看